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.

gox
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:

text
SessionConfig
{
    OnCreate func(session *gox.Session)
    OnExpire func(session *gox.ExpireSession)
}

Events

EventDescription
OnCreateIt runs when GOX creates a session.
OnExpireIt 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.

gox
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.

gox
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.

gox
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:

text
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.

gox
sessionID := session.ID()

Token() return the last token of the session.

gox
sessionToken := session.Token()

Both methods return an empty string when the session representation is not available.


Times

MethodDescription
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.
gox
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.

gox
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:

OutcomeMeaning
exists == true, err == nilThe key exists and the value was correctly assigned.
exists == false, err == nilThe key doesn't exist.
err != nilThe value could not be assigned or the reading was not completed.

Has() check if a key existed without regaining its value.

gox
if session.Has("authenticated") {
    log.Printf("Expiró una sesión autenticada")
}

GetAll() returns a copy of all available values.

gox
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:

gox
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 OnCreate to establish initial values common to all sessions.
  • Check the errors of the operations carried out within the callbacks.
  • Keep OnCreate and OnExpire breves.
  • It uses only the reading methods provided by ExpireSession.
  • Do not use OnExpire to process an explicit destruction.
  • Do not depend on order between different session events.
  • It performs slow tasks through an independent work system.

See also

Next step

Continue with Response to know how to control the HTTP response sent to the client.

Response