sessions
Gin middleware for session management with pluggable cookie, Redis, Memcached, MongoDB, GORM, and PostgreSQL backends.
Repository Health
Technical Analysis
gin-contrib/sessions is session-management middleware for the Gin web framework, wrapping Gorilla’s battle-tested gorilla/sessions package behind a Gin-native handler API. It registers a session (or several, independently named sessions) on the request context via sessions.Sessions(name, store) middleware, then exposes a simple Get/Set/Delete/Clear/AddFlash/Save interface inside route handlers through sessions.Default(c).
The defining feature is backend pluggability: the same Store interface is implemented by more than half a dozen store packages shipped in this repo — cookie-based (signed/encrypted, no server-side storage), Redis (via redigo or redistore), Memcached (both ASCII and binary/SASL protocols), MongoDB (via mgo or the official mongo-driver), GORM (any SQL dialect GORM supports), a dedicated PostgreSQL store, an in-memory memstore for tests, and a filesystem store. Swapping backends is a one-line change at store-construction time; application code that reads and writes session values never changes.
It also supports multiple concurrently-active sessions with different names and even different backend stores in the same request (SessionsMany / SessionsManyStores), which is useful for apps that need to separate, say, an authentication session from a shopping-cart or preference session with different lifetimes.
What You Get
- Store interface - a single
Storeinterface (sessions.Store+Options) that every backend implements identically, so handler code is backend-agnostic - Eight backend store packages - cookie, redis, memcached, mongo (mgo and mongo-driver variants), gorm, postgres, memstore, and filesystem, all in the same module
- Multi-session support -
SessionsManyandSessionsManyStoreslet a single request carry several independently named sessions, even backed by different stores - Flash messages -
AddFlash/Flashesfor one-time notices (e.g. post-redirect form errors) built on top of the same session value store - Cookie option control - a typed
Optionsstruct (domain, path, max age, secure, HTTP-only, SameSite) applied per-session viasession.Options(...) - Shared conformance test suite - the
testerpackage provides reusable test functions (GetSet,DeleteKey,Flashes,Clear,Options,Many) so every backend, including third-party ones, is exercised against the same behavioral contract
Common Use Cases
- Server-rendered login sessions - storing a signed-in user’s ID and role in an encrypted cookie session for a traditional Gin server-rendered app
- Horizontally-scaled API session storage - backing sessions with Redis or Memcached so session state is shared across multiple Gin instances behind a load balancer
- Flash-message-driven form flows - using
AddFlash/Flashesto surface validation errors or success banners after a redirect (POST-redirect-GET pattern) - Existing SQL-backed apps - persisting sessions in the same Postgres/MySQL/SQLite database an app already uses via the
gormorpostgresstore, avoiding a new infrastructure dependency - Multi-tenant or multi-concern sessions - keeping an auth session and a separate short-lived session (e.g. OAuth state, cart) alive at once with different names or stores in the same request
Under The Hood
Architecture
The package is organized as a thin core (sessions.go) plus a family of independent backend adapter packages (cookie/, redis/, memcached/, mongo/mongomgo, mongo/mongodriver, gorm/, postgres/, memstore/, filesystem/), each implementing the same sessions.Store interface by wrapping an underlying gorilla/sessions store type. The middleware constructors (Sessions, SessionsMany, SessionsManyStores) attach a session struct to the Gin context under a fixed key; that struct lazily resolves the underlying gorilla/sessions.Session on first access and tracks a written flag so Save() is a no-op when nothing changed. Swapping a backend means constructing a different Store implementation at setup time — no other code path changes, which is the core design intent of the whole module.
Tech Stack
Go module targeting a recent Go toolchain, built directly on gin-gonic/gin for the HTTP layer and gorilla/sessions (plus gorilla/context and gorilla/securecookie) for the underlying session/cookie primitives. Backend-specific dependencies are pulled in per adapter: gomodule/redigo and boj/redistore for Redis, bradfitz/gomemcache and memcachier/mc for Memcached, globalsign/mgo and the official go.mongodb.org/mongo-driver for MongoDB, gorm.io/gorm with dialect drivers (e.g. gorm.io/driver/sqlite) for the GORM store, and lib/pq for PostgreSQL. CI runs lint, tests, a Trivy security scan, and CodeQL via GitHub Actions, with releases automated through GoReleaser.
Code Quality
Each backend package ships its own _test.go file, and a shared tester package centralizes the actual test scenarios (get/set, delete, flash messages, clear, cookie options, multi-session) so every store — including third-party ones built against this interface — is validated against an identical behavioral contract rather than each backend inventing its own ad hoc tests. Error handling favors returning errors from Save() and logging via log/slog rather than panicking. Naming is consistent and idiomatic Go; the public surface area per backend is intentionally small (a NewStore constructor plus the shared interface).
What Makes It Unique Rather than being one session backend, this project is a conformance layer: it defines a shared interface and a shared test suite, then ships a comprehensive set of production-grade backend implementations behind it, ranging from zero-infrastructure cookie storage to distributed caches to full SQL persistence. That breadth, combined with the ability to run multiple independently-configured sessions in a single request, is unusual among Gin session middleware, most of which pick a single backend and stop there.
Used by 2 apps in this directory
Digger
Devops · Automation · Developer Tools
Run Terraform and OpenTofu natively inside your existing CI pipeline — no separate runners, no third-party secrets, no extra compute costs.
SafeLine
Security
Self-hosted WAF with a custom semantic detection engine and ML-powered threat analysis that blocks web attacks without cloud dependency.