gin-contrib/sessions

repository·master·Indexed 23 days ago

https://github.com/gin-contrib/sessions

A Gin middleware for session management supporting multiple backends including cookies, Redis, Memcached, MongoDB, GORM, PostgreSQL, and the local filesystem. It provides a Session interface for data manipulation and supports configuring single or multiple sessions via Sessions, SessionsMany, and SessionsManyStores middleware.

Tokens
2.9K
Snippets
4
Records
18
Agent score
81%

What's inside gin-contrib/sessions

  1. Register session middleware in Gin

    master

    To enable session management in your Gin application, use one of the following middleware functions. These functions attach session objects to the *gin.Context so they can be accessed within your handlers.

    • Sessions(name string, store Store): Registers a single session with the specified name using the provided store.
    • SessionsMany(names []string, store Store): Registers multiple sessions, all sharing the same store, using the provided list of names.
    • SessionsManyStores(sessionStores []SessionStore): Registers multiple sessions where each session can have its own unique name and its own specific Store implementation.
  2. How to use multiple sessions with the same store

    master

    To manage multiple independent sessions using the same backend store, use sessions.SessionsMany(names, store) as middleware. Access specific sessions in handlers using sessions.DefaultMany(c, name).

    package main
    
    import (
      "github.com/gin-contrib/sessions"
      "github.com/gin-contrib/sessions/cookie"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      r := gin.Default()
      store := cookie.NewStore([]byte("secret"))
      sessionNames := []string{"a", "b"}
      r.Use(sessions.SessionsMany(sessionNames, store))
    
      r.GET("/hello", func(c *gin.Context) {
        sessionA := sessions.DefaultMany(c, "a")
        sessionB := sessions.DefaultMany(c, "b")
    
        if sessionA.Get("hello") != "world!" {
          sessionA.Set("hello", "world!")
          sessionA.Save()
        }
    
        if sessionB.Get("hello") != "world?" {
          sessionB.Set("hello", "world?")
          sessionB.Save()
        }
    
        c.JSON(200, gin.H{
          "a": sessionA.Get("hello"),
          "b": sessionB.Get("hello"),
        })
      })
      r.Run(":8000")
    }
  3. How to use multiple sessions with different stores

    master

    To use different backends for different sessions (e.g., one session in cookies and another in Redis), use sessions.SessionsManyStores(stores) as middleware. The stores argument is a slice of sessions.SessionStore objects, which contain a Name and a Store.

    package main
    
    import (
      "github.com/gin-contrib/sessions"
      "github.com/gin-contrib/sessions/cookie"
      "github.com/gin-contrib/sessions/redis"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      r := gin.Default()
      cookieStore := cookie.NewStore([]byte("secret"))
      redisStore, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
      sessionStores := []sessions.SessionStore{
        {
          Name:  "a",
          Store: cookieStore,
        },
        {
          Name:  "b",
          Store: redisStore,
        },
      }
      r.Use(sessions.SessionsManyStores(sessionStores))
    
      r.GET("/hello", func(c *gin.Context) {
        sessionA := sessions.DefaultMany(c, "a")
        sessionB := sessions.DefaultMany(c, "b")
    
        if sessionA.Get("hello") != "world!" {
          sessionA.Set("hello", "world!")
          sessionA.Save()
        }
    
        if sessionB.Get("hello") != "world?" {
          sessionB.Set("hello", "world?")
          sessionB.Save()
        }
    
        c.JSON(200, gin.H{
          "a": sessionA.Get("hello"),
          "b": sessionB.Get("hello"),
        })
      })
      r.Run(":8000")
    }
  4. How to use a single session

    master

    To manage a single session, use sessions.Sessions(name, store) as middleware. You can access the session in handlers using sessions.Default(c).

    Note: Always call session.Save() after modifying session data to persist changes.

    package main
    
    import (
      "github.com/gin-contrib/sessions"
      "github.com/gin-contrib/sessions/cookie"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      r := gin.Default()
      store := cookie.NewStore([]byte("secret"))
      r.Use(sessions.Sessions("mysession", store))
    
      r.GET("/hello", func(c *gin.Context) {
        session := sessions.Default(c)
    
        if session.Get("hello") != "world" {
          session.Set("hello", "world")
          session.Save()
        }
    
        c.JSON(200, gin.H{"hello": session.Get("hello")})
      })
      r.Run(":8000")
    }
  5. Configure MongoDB session store

    master

    MongoDB support is available for both the legacy mgo driver and the modern mongo-driver.

    Using mgo

    import (
      "github.com/gin-contrib/sessions/mongo/mongomgo"
      "github.com/globalsign/mgo"
    )
    
    session, _ := mgo.Dial("localhost:27017/test")
    c := session.DB("").C("sessions")
    store := mongomgo.NewStore(c, 3600, true, []byte("secret"))

    Using mongo-driver

    import (
      "github.com/gin-contrib/sessions/mongo/mongodriver"
      "go.mongodb.org/mongo-driver/mongo"
    )
    
    // Assuming 'client' is an initialized *mongo.Client
    c := client.Database("test").Collection("sessions")
    store := mongodriver.NewStore(c, 3600, true, []byte("secret"))
  6. Configure Memcached session store

    master

    Memcached support is available via two protocols:

    ASCII Protocol

    Uses gomemcache/memcache.

    import (
      "github.com/bradfitz/gomemcache/memcache"
      "github.com/gin-contrib/sessions/memcached"
    )
    
    store := memcached.NewStore(memcache.New("localhost:11211"), "", []byte("secret"))

    Binary protocol (with SASL)

    Uses memcachier/mc.

    import (
      "github.com/gin-contrib/sessions/memcached"
      "github.com/memcachier/mc"
    )
    
    client := mc.NewMC("localhost:11211", "username", "password")
    store := memcached.NewMemcacheStore(client, "", []byte("secret"))
  7. Configure PostgreSQL session store

    master

    Use the postgres package to store sessions in a PostgreSQL database using the standard database/sql driver.

    import (
      "database/sql"
      "github.com/gin-contrib/sessions/postgres"
    )
    
    db, _ := sql.Open("postgres", "postgresql://username:password@localhost:5432/database")
    store, _ := postgres.NewStore(db, []byte("secret"))
  8. Configure GORM session store

    master

    Use the gorm package to store sessions in a database using GORM.

    import (
      "github.com/gin-contrib/sessions/gorm"
      "gorm.io/gorm"
    )
    
    // Assuming 'db' is an initialized *gorm.DB
    store := gormsessions.NewStore(db, true, []byte("secret"))
  9. Manage session data with the Session interface

    master

    The Session interface provides methods to manipulate session data. Note that most operations (Set, Delete, Clear, AddFlash, Options) mark the session as 'dirty', but you must call Save() to persist changes to the underlying store.

    Methods

    • ID() string: Returns the unique session ID.
    • Get(key interface{}) interface{}: Retrieves the value associated with the given key.
    • Set(key interface{}, val interface{}): Sets a value for the given key.
    • Delete(key interface{}): Removes a specific key.
    • Clear(): Removes all values from the session.
    • AddFlash(value interface{}, vars ...string): Adds a flash message. If vars is empty, the default key _flash is used.
    • Flashes(vars ...string) []interface{}: Retrieves flash messages. If vars is empty, it reads from _flash.
    • Options(Options): Configures session options (like MaxAge, Path, etc.).
    • Save() error: Persists the session changes to the store.