Skip to content
You are reading the v0.20 documentation. Go to the latest version (v1.0)

The basics

Sessions

Encrypted cookie, memory and database session stores with flash messages and old input.

Last updated:

vukem.DefaultMiddleware installs the session middleware on the router stack; app.Sessions() builds the *session.Manager from SESSION_* variables.

Configuration#

VariableDefaultNotes
SESSION_DRIVERcookiecookie (data encrypted in the cookie) or memory
SESSION_LIFETIME24hAbsolute lifetime
SESSION_IDLE_TIMEOUT2hExpires after inactivity
SESSION_COOKIEvukem_sessionCookie name
SESSION_SECUREautoauto = secure in production or when APP_URL is https://

Stores#

StorePackageNotes
CookiesessionAES-256-GCM with a key derived from APP_KEY (HKDF); tampered cookies are rejected and logged as session.invalid
Memorysession.NewMemoryStore()Tests and development
Databasesession.NewSQLStore(db, opts...)sessions table (SQLite or PostgreSQL with WithDollarPlaceholders()); install with app.SetSessionStore before the first request
Redisdrivers/redisvukem.WithSessionStore(rc.SessionStore(""))

Usage#

Go
func (a *AuthController) Login(c *web.Ctx) error {
	// …verify credentials…
	s := c.Session()
	s.Regenerate()             // new id, keep data: prevents session fixation
	s.Put("user_id", user.ID)
	_ = c.Flash("success", "Welcome back!")

	return c.RedirectRoute("dashboard")
}
MethodMeaning
Get(key), Put(key, v), Forget(keys...), Pull(key)Read, write, remove, read-and-remove (values must be JSON-compatible)
Flash(key, v)Available on the next request only
Regenerate()New id, same data: call on login and privilege changes
Invalidate()Clear everything and issue a new id: call on logout

c.Flash(key, v) returns an error when no session middleware is installed; c.FlashValue(key) reads a flashed value.

Validation errors and old input#

When a form post fails validation, the session's validation hook flashes the field errors and the submitted input, then redirects back. On the next request:

Go
c.Errors()       // map[string][]string
c.Old("title")   // previous value; dotted paths for nested fields ("author.email")

In views use {{error "title"}}, {{errors}} and {{old "title"}}. Password fields, _token and _method are never flashed.

Behaviour#

  • Lazy: nothing is read or written unless the handler uses the session; an untouched session writes no cookie.
  • Idle and absolute timeouts; the idle timestamp is refreshed at most once a minute.
  • Cookies are HttpOnly, SameSite=Lax, Secure per SESSION_SECURE. Cookie session data over 4 KB is not saved and is logged as an error (session.ErrCookieTooLarge); switch to a server-side store.