Events
Session events allow you to run logic when GOX creates or expires a session.
The callbacks are configured by server.Config.Session And GOX runs them automatically.
func SetGoxConfig() server.Config {
return server.Config{
Session: server.SessionConfig{
OnCreate: func(session *gox.Session) {
if err := session.Set("language", "es"); err != nil {
log.Printf("No se pudo inicializar la sesión: %v", err)
}
},
OnExpire: func(session *gox.ExpireSession) {
log.Printf("La sesión %s expiró", session.ID())
},
},
}
} OnCreate is given an active session that can be modified. OnExpire received a reading-only representation with the information that the session had when it expired.
Structure
The session configuration provides the following events:
SessionConfig
{
OnCreate func(session *gox.Session)
OnExpire func(session *gox.ExpireSession)
} Events
| Event | Description |
|---|---|
| OnCreate | It runs when GOX creates a session. |
| OnExpire | It runs when a session expires by inactivity. |
OnCreate
Firma:func(session *gox.Session)
OnCreate it runs after creating a session and before continuing with the request that originated it.
func SetGoxConfig() server.Config {
return server.Config{
Session: server.SessionConfig{
OnCreate: func(session *gox.Session) {
if err := session.Set("language", "es"); err != nil {
log.Printf("No se pudo guardar el idioma: %v", err)
}
if err := session.Set("theme", "light"); err != nil {
log.Printf("No se pudo guardar el tema: %v", err)
}
},
},
}
} The callback receives the same active session that will later be available by ctx.Session.
You can use your methods to store values, modify the TTL or consult your identity.
OnCreate: func(session *gox.Session) {
if err := session.Set("createdBy", "George"); err != nil {
log.Printf("No se pudo inicializar la sesión: %v", err)
return
}
session.SetTTL(24 * time.Hour)
log.Printf("Sesión creada: %s", session.ID)
}, The changes made in the OnCreate are available for Page, Action or WebSocket when it continues to run.
OnCreate It runs only when creating a session. Recover an existing session does not run the callback again.
GOX creates a session when it does not receive valid credentials to recover an existing one. Lifecycle to know the process of creation and recovery.
OnCreate The errors produced by the operations carried out within the callback must be processed in the callback itself.
OnExpire
Firma:func(session *gox.ExpireSession)
OnExpire is run once when a session reaches its expiry time per inactivity.
func SetGoxConfig() server.Config {
return server.Config{
Session: server.SessionConfig{
OnExpire: func(session *gox.ExpireSession) {
log.Printf("La sesión %s expiró", session.ID())
},
},
}
} The callback receives a read-only snapshot that retains the identity, times and values stored by the session.
The session can no longer be renewed or changed from OnExpire.
OnExpire does not run when the session is explicitly deleted by Destroy(). Destruction and expiry are different events.
The associated WebSocket connections are closed when the session expires.
ExpireSession
ExpireSession provides the following methods:
ExpireSession
{
ID() string
Token() string
CreatedAt() time.Time
LastUpdate() time.Time
ExpireAt() time.Time
GetTTL() time.Duration
Get(key string, out any) (bool, error)
Has(key string) bool
GetAll() map[string]any
} It does not provide methods for storing, removing or modifying values.
Identity
ID() returns the expired session identifier.
sessionID := session.ID() Token() return the last token of the session.
sessionToken := session.Token() Both methods return an empty string when the session representation is not available.
Times
| Method | Description |
|---|---|
CreatedAt() | It returns the time the session was set up. |
LastUpdate() | Returns the time of your last registered update. |
ExpireAt() | It returns the time the session expired. |
GetTTL() | Returns the TTL I had configured. |
OnExpire: func(session *gox.ExpireSession) {
log.Printf(
"Sesión creada en %s y expirada en %s",
session.CreatedAt(),
session.ExpireAt(),
)
}, CreatedAt(), LastUpdate() and ExpireAt() return type values time.Time. GetTTL() returns a type value time.Duration.
GetTTL() returns the set duration, not the total time the session remained active.
See TTL to know how the expiry is determined and renewed.
Stored values
Get(), Has() and GetAll() allow to consult the values that the session had when it expired.
OnExpire: func(session *gox.ExpireSession) {
var userName string
exists, err := session.Get("userName", &userName)
if err != nil {
log.Printf("No se pudo leer la sesión: %v", err)
return
}
if exists {
log.Printf("Expiró la sesión de %s", userName)
}
}, Get() uses the same contract as Session Storage:
| Outcome | Meaning |
|---|---|
exists == true, err == nil | The key exists and the value was correctly assigned. |
exists == false, err == nil | The key doesn't exist. |
err != nil | The value could not be assigned or the reading was not completed. |
Has() check if a key existed without regaining its value.
if session.Has("authenticated") {
log.Printf("Expiró una sesión autenticada")
} GetAll() returns a copy of all available values.
values := session.GetAll() Modifying the returned map does not change the session or restart its values.
See Session Storage to know the behavior of these operations.
Full example
The following example initiates each session and records information when it expires:
func SetGoxConfig() server.Config {
return server.Config{
Session: server.SessionConfig{
TTL: 3 * time.Hour,
OnCreate: func(session *gox.Session) {
if err := session.Set("language", "es"); err != nil {
log.Printf("No se pudo inicializar la sesión: %v", err)
}
},
OnExpire: func(session *gox.ExpireSession) {
var userName string
exists, err := session.Get("userName", &userName)
if err != nil {
log.Printf("No se pudo leer la sesión expirada: %v", err)
return
}
if exists {
log.Printf("La sesión de %s expiró", userName)
}
},
},
}
} See Configuration to know the complete server configuration.
Best practices
- Use
OnCreateto establish initial values common to all sessions. - Check the errors of the operations carried out within the callbacks.
- Keep
OnCreateandOnExpirebreves. - It uses only the reading methods provided by
ExpireSession. - Do not use
OnExpireto process an explicit destruction. - Do not depend on order between different session events.
- It performs slow tasks through an independent work system.