sessions

package
v0.4.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package sessions provides cookie-based session management for ada.

It is an idiomatic, dependency-free alternative to gorilla/sessions, built on the github.com/rakunlabs/ada/securecookie codec. Session values use string keys, matching the rest of ada.

Typical use with the cookie store:

store := sessions.NewCookieStore(hashKey, blockKey)

sess, _ := store.Get(r, "auth")
sess.Values["user"] = "ada"
if err := sess.Save(r, w); err != nil {
	// handle error
}

To share session state across a request (and to use sessions.Save to flush every touched session at once), wrap handlers with sessions.Middleware.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware installs a per-request session registry. With it in place, repeated Store.Get calls for the same name share one *Session and a single sessions.Save flushes every touched session.

func NewContext

func NewContext(ctx context.Context) context.Context

NewContext returns a copy of ctx carrying a fresh, empty session registry.

func Save

func Save(r *http.Request, w http.ResponseWriter) error

Save persists every session registered during the request. It is a no-op when Middleware was not installed; in that case call Session.Save directly.

Types

type CookieStore

type CookieStore struct {
	// Codecs sign and encrypt the cookie payload. The first codec is used for
	// encoding; all are tried when decoding, which enables key rotation.
	Codecs securecookie.Codecs

	// Options is the template applied to every session created by this store.
	Options *Options
}

CookieStore stores the entire session, including its values, in the cookie itself. The payload is signed and (when a block key is supplied) encrypted by securecookie, so it cannot be read or tampered with by the client.

Because everything lives in the cookie, total size is limited (~4KB per cookie). For large payloads use a server-side store instead.

func NewCookieStore

func NewCookieStore(keyPairs ...[]byte) *CookieStore

NewCookieStore returns a CookieStore using the given key pairs. Each pair is (hashKey, blockKey): the hash key authenticates the cookie (use 32 or 64 random bytes) and the optional block key encrypts it (16, 24 or 32 bytes).

store := sessions.NewCookieStore(
	securecookie.GenerateRandomKey(64), securecookie.GenerateRandomKey(32),
)

Pass several pairs to rotate keys: the first pair signs new cookies, the rest are accepted when decoding old ones.

func (*CookieStore) Get

func (s *CookieStore) Get(r *http.Request, name string) (*Session, error)

Get returns the session for name, reusing a request-cached instance when a registry is installed (see Middleware).

func (*CookieStore) MaxAge

func (s *CookieStore) MaxAge(age int)

MaxAge sets the max age for both the session cookie and the underlying codecs so the cookie's lifetime and the signature's validity window stay in sync. Call it at setup time.

func (*CookieStore) New

func (s *CookieStore) New(r *http.Request, name string) (*Session, error)

New loads the session from the request cookie. If the cookie is missing or cannot be decoded, it returns a fresh empty session (with IsNew=true); a decode failure is also returned as the error.

func (*CookieStore) Save

func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter, sess *Session) error

Save encodes the session values into the response cookie. If Options.MaxAge is negative the cookie is deleted instead.

type Options

type Options struct {
	Path        string
	Domain      string
	MaxAge      int // seconds; 0 = session cookie; <0 deletes the cookie
	Secure      bool
	HttpOnly    bool
	Partitioned bool
	SameSite    http.SameSite
}

Options controls the attributes of a session cookie.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry caches the sessions touched during a single request so that repeated Store.Get calls return the same instance and Save can flush them all at once.

func GetRegistry

func GetRegistry(r *http.Request) *Registry

GetRegistry returns the per-request registry installed by Middleware, or nil if none is present.

type Session

type Session struct {
	// ID is an optional identifier set by server-side stores. The cookie store
	// leaves it empty.
	ID string

	// Values is the session payload. Keys are strings.
	Values map[string]any

	// Options controls the Set-Cookie attributes for this session.
	Options *Options

	// IsNew reports whether the session was created during this request rather
	// than loaded from an existing cookie.
	IsNew bool
	// contains filtered or unexported fields
}

Session holds the data for a single session.

func NewSession

func NewSession(store Store, name string) *Session

NewSession returns an empty session bound to store under name. Stores use it from their New method; application code normally calls Store.Get instead.

func (*Session) AddFlash

func (s *Session) AddFlash(value any, vars ...string)

AddFlash queues a flash message. Flash messages are read once: the next call to Flashes returns and clears them.

Pass an optional key to use a separate bucket instead of the default one.

func (*Session) Flashes

func (s *Session) Flashes(vars ...string) []any

Flashes returns and removes the queued flash messages. Pass an optional key to read a non-default bucket. It returns nil when there are none.

func (*Session) Name

func (s *Session) Name() string

Name returns the session name (the cookie name it is stored under).

func (*Session) Save

func (s *Session) Save(r *http.Request, w http.ResponseWriter) error

Save is a convenience wrapper around the store's Save method.

func (*Session) Store

func (s *Session) Store() Store

Store returns the store this session belongs to.

type Store

type Store interface {
	// Get returns a cached session for the request if one exists, otherwise it
	// behaves like New. When a per-request registry is installed (see
	// Middleware), repeated calls with the same name return the same instance.
	Get(r *http.Request, name string) (*Session, error)

	// New always returns a fresh session loaded from the request, if present.
	// On a decode failure it returns a new empty session together with the
	// error so the caller can decide how to react.
	New(r *http.Request, name string) (*Session, error)

	// Save writes the session to the response. A session whose Options.MaxAge is
	// negative is deleted.
	Save(r *http.Request, w http.ResponseWriter, s *Session) error
}

Store persists sessions. Implementations decide where the data lives (in the cookie, on disk, in a database, ...).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL