sessions

Gin middleware for session management with pluggable cookie, Redis, Memcached, MongoDB, GORM, and PostgreSQL backends.

Library
Go
vv1.1.1
1,568stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
71/100Good
Development Activity72
Maintenance48
Community64
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
77/100Good
Architecture82
Code Quality78
Innovation62
Learning Curve85

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 Store interface (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 - SessionsMany and SessionsManyStores let a single request carry several independently named sessions, even backed by different stores
  • Flash messages - AddFlash/Flashes for one-time notices (e.g. post-redirect form errors) built on top of the same session value store
  • Cookie option control - a typed Options struct (domain, path, max age, secure, HTTP-only, SameSite) applied per-session via session.Options(...)
  • Shared conformance test suite - the tester package 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/Flashes to 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 gorm or postgres store, 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.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search