Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

scs

> 编程语言
Open source

HTTP Session Management for Go

2.6K stars0 likes0 views
WebsiteGitHub

About

HTTP Session Management for Go

SCS: HTTP Session Management for Go

Features

  • Automatic loading and saving of session data via middleware.
  • Choice of 19 different server-side session stores including PostgreSQL, MySQL, MSSQL, SQLite, Redis and many others. Custom session stores are also supported.
  • Supports multiple sessions per request, 'flash' messages, session token regeneration, idle and absolute session timeouts, and 'remember me' functionality.
  • Easy to extend and customize. Communicate session tokens to/from clients in HTTP headers or request/response bodies.
  • Efficient design. Smaller, faster and uses less memory than gorilla/sessions.

Project status

This project has reached a stable status. It is actively maintained with ongoing bug fixes and essential updates, and significant alterations to the API or behavior are not expected. Please see the contributing guidelines before submitting any PRs.

Instructions

  • SCS: HTTP Session Management for Go
    • Features
    • Instructions
      • Installation
      • Basic Use
      • Configuring Session Behavior
      • Working with Session Data
      • Loading and Saving Sessions
      • Configuring the Session Store
      • Using Custom Session Stores
        • Using Custom Session Stores (with context.Context)
      • Multiple Sessions per Request
      • Enumerate All Sessions
      • Multiple Writes, Flushing and Streaming Responses
      • Hijacking Responses
      • Compatibility
      • Contributing

Installation

This package requires Go 1.12 or newer.

bash
go get github.com/alexedwards/scs/v2

Note: If you're using the traditional GOPATH mechanism to manage dependencies, instead of modules, you'll need to go get and import github.com/alexedwards/scs without the v2 suffix.

Please use versioned releases. Code in tip may contain experimental features which are subject to change.

Basic Use

SCS implements a session management pattern following the OWASP security guidelines. Session data is stored on the server, and a randomly-generated unique session token (or session ID) is communicated to and from the client in a session cookie.

…
$ curl -i --cookie-jar cj --cookie cj localhost:4000/put
HTTP/1.1 200 OK
Cache-Control: no-cache="Set-Cookie"
Set-Cookie: session=lHqcPNiQp_5diPxumzOklsSdE-MJ7zyU6kjch1Ee0UM; Path=/; Expires=Sat, 27 Apr 2019 10:28:20 GMT; Max-Age=86400; HttpOnly; SameSite=Lax
Vary: Cookie
Date: Fri, 26 Apr 2019 10:28:19 GMT
Content-Length: 0

$ curl -i --cookie-jar cj --cookie cj localhost:4000/get
HTTP/1.1 200 OK
Date: Fri, 26 Apr 2019 10:28:24 GMT
Content-Length: 21
Content-Type: text/plain; charset=utf-8

Hello from a session!

Configuring Session Behavior

Session behavior can be configured via the SessionManager fields.

go
sessionManager = scs.New()
sessionManager.Lifetime = 3 * time.Hour
sessionManager.IdleTimeout = 20 * time.Minute
sessionManager.Cookie.Name = "session_id"
sessionManager.Cookie.Domain = "example.com"
sessionManager.Cookie.HttpOnly = true
sessionManager.Cookie.Path = "/example/"
sessionManager.Cookie.Persist = true
sessionManager.Cookie.SameSite = http.SameSiteStrictMode
sessionManager.Cookie.Secure = true
sessionManager.Cookie.Partitioned = true

Documentation for all available settings and their default values can be found here.

Working with Session Data

Data can be set using the Put() method and retrieved with the Get() method. A variety of helper methods like GetString(), GetInt() and GetBytes() are included for common data types. Please see the documentation for a full list of helper methods.

The Pop() method (and accompanying helpers for common data types) act like a one-time Get(), retrieving the data and removing it from the session in one step. These are useful if you want to implement 'flash' message functionality in your application, where messages are displayed to the user once only.

Some other useful functions are Exists() (which returns a bool indicating whether or not a given key exists in the session data) and Keys() (which returns a sorted slice of keys in the session data).

Individual data items can be deleted from the session using the Remove() method. Alternatively, all session data can be deleted by using the Destroy() method. After calling Destroy(), any further operations in the same request cycle will result in a new session being created --- with a new session token and a new lifetime.

Behind the scenes SCS uses gob encoding to store session data, so if you want to store custom types in the session data they must be registered with the encoding/gob package first. Struct fields of custom types must also be exported so that they are visible to the encoding/gob package. Please see here for a working example.

Loading and Saving Sessions

Most applications will use the LoadAndSave() middleware. This middleware takes care of loading and committing session data to the session store, and communicating the session token to/from the client in a cookie as necessary.

If you want to customize the behavior (like communicating the session token to/from the client in a HTTP header, or creating a distributed lock on the session token for the duration of the request) you are encouraged to create your own alternative middleware using the code in LoadAndSave() as a template. An example is given here.

Or for more fine-grained control you can load and save sessions within your individual handlers (or from anywhere in your application). See here for an example.

Configuring the Session Store

By default SCS uses an in-memory store for session data. This is convenient (no setup!) and very fast, but all session data will be lost when your application is stopped or restarted. Therefore it's useful for applications where data loss is an acceptable trade off for fast performance, or for prototyping and testing purposes. In most production applications you will want to use a persistent session store like PostgreSQL or MySQL instead.

The session stores currently included are shown in the table below. Please click the links for usage instructions and examples.

Package Backend Embedded In-Memory Multi-Process
badgerstore BadgerDB Y N N
boltstore BBolt Y N N
bunstore Bun (ORM for PostgreSQL/MySQL/MSSQL/SQLite) N N Y
buntdbstore BuntDB Y Y N
cockroachdbstore CockroachDB N N Y
consulstore Consul N Y Y
etcdstore Etcd N N Y
firestore Google Cloud Firestore N ? Y
gormstore GORM (ORM for PostgreSQL/MySQL/SQLite/MSSQL/TiDB) N N Y
leveldbstore LevelDB Y N N
memstore In-memory (default) Y Y N
mongodbstore MongoDB N N Y
mssqlstore Microsoft SQL Server N N Y
mysqlstore MySQL N N Y
pgxstore PostgreSQL (using the pgx driver) N N Y
postgresstore PostgreSQL (using the pq or pgx/v5/stdlib drivers) N N Y
goredisstore Redis (using the go-redis driver) N Y Y
redisstore Redis (using the redigo driver) N Y Y
[sqlite3store](https://github

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gocontextgogolanghttp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言