session

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package session provides cookie-backed sessions modelled on Laravel's Session facade.

A session is a map[string]any persisted server-side under an opaque ID. The client carries the ID in an HttpOnly+Secure cookie. The default store is in-memory (suitable for single-replica apps and tests); the Store interface is small enough that a Redis or DB driver can plug in without changing call sites.

Sessions are short-lived: the cookie's MaxAge equals the store's TTL, and stale records are GC'd in the background. To survive restarts or run multi-replica, swap NewMemoryStore() for an external store implementation.

Index

Constants

This section is empty.

Variables

View Source
var ErrMissing = errors.New("session: key not set")

ErrMissing is returned by Get when the requested key isn't set.

Functions

This section is empty.

Types

type Manager

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

Manager owns the cookie configuration and a Store. A single Manager is shared across requests; per-request access happens through Session below.

func NewManager

func NewManager(store Store, opts Options) *Manager

NewManager returns a Manager with the given store and options.

func (*Manager) Middleware

func (m *Manager) Middleware() func(http.Handler) http.Handler

Middleware returns a framework-agnostic net/http middleware. It starts the session at the top of each request, makes the *Session available via session.FromRequest(r), and saves the session before the handler returns.

The middleware is compatible with any router that speaks the stdlib http.Handler interface (Gin, Fiber adapters, Chi, Echo, plain net/http, lagodev's web package). Use it once per app:

mw := session.Middleware(mgr)
mux.Handle("/", mw(http.HandlerFunc(handler)))

If Save fails (store unreachable), the failure is silently absorbed — the response has already begun streaming by the time the handler returns. Wrap a custom logger via FailureHandler if you need to be notified.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context, r *http.Request) (*Session, error)

Start returns the Session for r. If the request carries a valid session cookie, the existing data is loaded; otherwise a fresh session is created with a new ID. Call Save(w) before responding to persist any changes and (re-)issue the cookie.

type MemoryStore

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

MemoryStore is a sync.RWMutex-backed in-process Store with lazy expiry and a periodic sweeper.

func NewMemoryStore

func NewMemoryStore(defaultTTL time.Duration) *MemoryStore

NewMemoryStore returns a MemoryStore with the given default TTL. Pass 0 for "no expiry" (entries live until Destroy).

func (*MemoryStore) Close

func (s *MemoryStore) Close()

Close stops the background sweeper.

func (*MemoryStore) Destroy

func (s *MemoryStore) Destroy(_ context.Context, id string) error

func (*MemoryStore) Read

func (s *MemoryStore) Read(_ context.Context, id string) (map[string]any, bool, error)

func (*MemoryStore) Write

func (s *MemoryStore) Write(_ context.Context, id string, data map[string]any, ttl time.Duration) error

type Options

type Options struct {
	CookieName string
	TTL        time.Duration
	Insecure   bool // when true, cookies are not marked Secure
	SameSite   http.SameSite
}

Options configures Manager. Zero values use safe defaults (cookie="lagodev_session", TTL=2h, Secure=true, SameSite=Lax).

Note the inverted `Insecure` flag: cookies default to Secure=true so production code is correct without extra setup. Pass Insecure=true only for local HTTP development.

type Session

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

Session is the per-request handle. Not safe for concurrent use across goroutines.

func FromContext

func FromContext(ctx context.Context) *Session

FromContext is the bare-ctx variant. Returns nil when no session is attached.

func FromRequest

func FromRequest(r *http.Request) *Session

FromRequest pulls the *Session attached by Middleware. Returns nil if the middleware was not applied to the request.

func (*Session) All

func (s *Session) All() map[string]any

All returns a copy of the session data.

func (*Session) Destroy

func (s *Session) Destroy(ctx context.Context, w http.ResponseWriter) error

Destroy removes the session from the store and expires the cookie.

func (*Session) Flush

func (s *Session) Flush()

Flush clears the session contents (the ID is preserved).

func (*Session) Forget

func (s *Session) Forget(key string)

Forget removes a key.

func (*Session) Get

func (s *Session) Get(key string) (any, bool)

Get retrieves a value. ok=false when the key is missing.

func (*Session) GetString

func (s *Session) GetString(key string) string

GetString is a convenience for string-typed values; returns "" if the key is missing or the wrong type.

func (*Session) ID

func (s *Session) ID() string

ID returns the opaque session identifier.

func (*Session) IsNew

func (s *Session) IsNew() bool

IsNew reports whether the session was created during this request (no prior cookie or stale cookie).

func (*Session) Put

func (s *Session) Put(key string, value any)

Put stores a value, marking the session dirty.

func (*Session) Regenerate

func (s *Session) Regenerate(ctx context.Context) error

Regenerate issues a new session ID, preserving the data. Call after privilege escalation (login/logout) to mitigate session fixation.

func (*Session) Save

func (s *Session) Save(ctx context.Context, w http.ResponseWriter) error

Save persists pending changes (if any) and writes the cookie. Always safe to call.

type Store

type Store interface {
	// Read returns the session data for id. ok=false on miss.
	Read(ctx context.Context, id string) (map[string]any, bool, error)
	// Write replaces the session data for id. ttl=0 means use the
	// store's default.
	Write(ctx context.Context, id string, data map[string]any, ttl time.Duration) error
	// Destroy removes the session.
	Destroy(ctx context.Context, id string) error
}

Store persists per-session data. Implementations must be safe for concurrent use.

Jump to

Keyboard shortcuts

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