...

Text file src/github.com/gin-contrib/sessions/README.md

Documentation: github.com/gin-contrib/sessions

     1# sessions
     2
     3[![Run CI Lint](https://github.com/gin-contrib/sessions/actions/workflows/lint.yml/badge.svg)](https://github.com/gin-contrib/sessions/actions/workflows/lint.yml)
     4[![Run Testing](https://github.com/gin-contrib/sessions/actions/workflows/testing.yml/badge.svg)](https://github.com/gin-contrib/sessions/actions/workflows/testing.yml)
     5[![codecov](https://codecov.io/gh/gin-contrib/sessions/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-contrib/sessions)
     6[![Go Report Card](https://goreportcard.com/badge/github.com/gin-contrib/sessions)](https://goreportcard.com/report/github.com/gin-contrib/sessions)
     7[![GoDoc](https://godoc.org/github.com/gin-contrib/sessions?status.svg)](https://godoc.org/github.com/gin-contrib/sessions)
     8[![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin)
     9
    10Gin middleware for session management with multi-backend support:
    11
    12- [cookie-based](#cookie-based)
    13- [Redis](#redis)
    14- [memcached](#memcached)
    15- [MongoDB](#mongodb)
    16- [GoRM](#gorm)
    17- [memstore](#memstore)
    18- [PostgreSQL](#postgresql)
    19
    20## Usage
    21
    22### Start using it
    23
    24Download and install it:
    25
    26```bash
    27go get github.com/gin-contrib/sessions
    28```
    29
    30Import it in your code:
    31
    32```go
    33import "github.com/gin-contrib/sessions"
    34```
    35
    36## Basic Examples
    37
    38### single session
    39
    40```go
    41package main
    42
    43import (
    44  "github.com/gin-contrib/sessions"
    45  "github.com/gin-contrib/sessions/cookie"
    46  "github.com/gin-gonic/gin"
    47)
    48
    49func main() {
    50  r := gin.Default()
    51  store := cookie.NewStore([]byte("secret"))
    52  r.Use(sessions.Sessions("mysession", store))
    53
    54  r.GET("/hello", func(c *gin.Context) {
    55    session := sessions.Default(c)
    56
    57    if session.Get("hello") != "world" {
    58      session.Set("hello", "world")
    59      session.Save()
    60    }
    61
    62    c.JSON(200, gin.H{"hello": session.Get("hello")})
    63  })
    64  r.Run(":8000")
    65}
    66```
    67
    68### multiple sessions
    69
    70```go
    71package main
    72
    73import (
    74  "github.com/gin-contrib/sessions"
    75  "github.com/gin-contrib/sessions/cookie"
    76  "github.com/gin-gonic/gin"
    77)
    78
    79func main() {
    80  r := gin.Default()
    81  store := cookie.NewStore([]byte("secret"))
    82  sessionNames := []string{"a", "b"}
    83  r.Use(sessions.SessionsMany(sessionNames, store))
    84
    85  r.GET("/hello", func(c *gin.Context) {
    86    sessionA := sessions.DefaultMany(c, "a")
    87    sessionB := sessions.DefaultMany(c, "b")
    88
    89    if sessionA.Get("hello") != "world!" {
    90      sessionA.Set("hello", "world!")
    91      sessionA.Save()
    92    }
    93
    94    if sessionB.Get("hello") != "world?" {
    95      sessionB.Set("hello", "world?")
    96      sessionB.Save()
    97    }
    98
    99    c.JSON(200, gin.H{
   100      "a": sessionA.Get("hello"),
   101      "b": sessionB.Get("hello"),
   102    })
   103  })
   104  r.Run(":8000")
   105}
   106```
   107
   108## Backend Examples
   109
   110### cookie-based
   111
   112```go
   113package main
   114
   115import (
   116  "github.com/gin-contrib/sessions"
   117  "github.com/gin-contrib/sessions/cookie"
   118  "github.com/gin-gonic/gin"
   119)
   120
   121func main() {
   122  r := gin.Default()
   123  store := cookie.NewStore([]byte("secret"))
   124  r.Use(sessions.Sessions("mysession", store))
   125
   126  r.GET("/incr", func(c *gin.Context) {
   127    session := sessions.Default(c)
   128    var count int
   129    v := session.Get("count")
   130    if v == nil {
   131      count = 0
   132    } else {
   133      count = v.(int)
   134      count++
   135    }
   136    session.Set("count", count)
   137    session.Save()
   138    c.JSON(200, gin.H{"count": count})
   139  })
   140  r.Run(":8000")
   141}
   142```
   143
   144### Redis
   145
   146```go
   147package main
   148
   149import (
   150  "github.com/gin-contrib/sessions"
   151  "github.com/gin-contrib/sessions/redis"
   152  "github.com/gin-gonic/gin"
   153)
   154
   155func main() {
   156  r := gin.Default()
   157  store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
   158  r.Use(sessions.Sessions("mysession", store))
   159
   160  r.GET("/incr", func(c *gin.Context) {
   161    session := sessions.Default(c)
   162    var count int
   163    v := session.Get("count")
   164    if v == nil {
   165      count = 0
   166    } else {
   167      count = v.(int)
   168      count++
   169    }
   170    session.Set("count", count)
   171    session.Save()
   172    c.JSON(200, gin.H{"count": count})
   173  })
   174  r.Run(":8000")
   175}
   176```
   177
   178### Memcached
   179
   180#### ASCII Protocol
   181
   182```go
   183package main
   184
   185import (
   186  "github.com/bradfitz/gomemcache/memcache"
   187  "github.com/gin-contrib/sessions"
   188  "github.com/gin-contrib/sessions/memcached"
   189  "github.com/gin-gonic/gin"
   190)
   191
   192func main() {
   193  r := gin.Default()
   194  store := memcached.NewStore(memcache.New("localhost:11211"), "", []byte("secret"))
   195  r.Use(sessions.Sessions("mysession", store))
   196
   197  r.GET("/incr", func(c *gin.Context) {
   198    session := sessions.Default(c)
   199    var count int
   200    v := session.Get("count")
   201    if v == nil {
   202      count = 0
   203    } else {
   204      count = v.(int)
   205      count++
   206    }
   207    session.Set("count", count)
   208    session.Save()
   209    c.JSON(200, gin.H{"count": count})
   210  })
   211  r.Run(":8000")
   212}
   213```
   214
   215#### Binary protocol (with optional SASL authentication)
   216
   217```go
   218package main
   219
   220import (
   221  "github.com/gin-contrib/sessions"
   222  "github.com/gin-contrib/sessions/memcached"
   223  "github.com/gin-gonic/gin"
   224  "github.com/memcachier/mc"
   225)
   226
   227func main() {
   228  r := gin.Default()
   229  client := mc.NewMC("localhost:11211", "username", "password")
   230  store := memcached.NewMemcacheStore(client, "", []byte("secret"))
   231  r.Use(sessions.Sessions("mysession", store))
   232
   233  r.GET("/incr", func(c *gin.Context) {
   234    session := sessions.Default(c)
   235    var count int
   236    v := session.Get("count")
   237    if v == nil {
   238      count = 0
   239    } else {
   240      count = v.(int)
   241      count++
   242    }
   243    session.Set("count", count)
   244    session.Save()
   245    c.JSON(200, gin.H{"count": count})
   246  })
   247  r.Run(":8000")
   248}
   249```
   250
   251### MongoDB
   252
   253#### mgo
   254```go
   255package main
   256
   257import (
   258  "github.com/gin-contrib/sessions"
   259  "github.com/gin-contrib/sessions/mongo/mongomgo"
   260  "github.com/gin-gonic/gin"
   261  "github.com/globalsign/mgo"
   262)
   263
   264func main() {
   265  r := gin.Default()
   266  session, err := mgo.Dial("localhost:27017/test")
   267  if err != nil {
   268    // handle err
   269  }
   270
   271  c := session.DB("").C("sessions")
   272  store := mongomgo.NewStore(c, 3600, true, []byte("secret"))
   273  r.Use(sessions.Sessions("mysession", store))
   274
   275  r.GET("/incr", func(c *gin.Context) {
   276    session := sessions.Default(c)
   277    var count int
   278    v := session.Get("count")
   279    if v == nil {
   280      count = 0
   281    } else {
   282      count = v.(int)
   283      count++
   284    }
   285    session.Set("count", count)
   286    session.Save()
   287    c.JSON(200, gin.H{"count": count})
   288  })
   289  r.Run(":8000")
   290}
   291```
   292
   293#### mongo-driver
   294```
   295package main
   296
   297import (
   298  "context"
   299  "github.com/gin-contrib/sessions"
   300  "github.com/gin-contrib/sessions/mongo/mongodriver"
   301  "github.com/gin-gonic/gin"
   302  "go.mongodb.org/mongo-driver/mongo"
   303  "go.mongodb.org/mongo-driver/mongo/options"
   304)
   305
   306func main() {
   307  r := gin.Default()
   308  mongoOptions := options.Client().ApplyURI("mongodb://localhost:27017")
   309  client, err := mongo.NewClient(mongoOptions)
   310  if err != nil {
   311    // handle err
   312  }
   313
   314  if err := client.Connect(context.Background()); err != nil {
   315    // handle err
   316  }
   317
   318  c := client.Database("test").Collection("sessions")
   319  store := mongodriver.NewStore(c, 3600, true, []byte("secret"))
   320  r.Use(sessions.Sessions("mysession", store))
   321
   322  r.GET("/incr", func(c *gin.Context) {
   323    session := sessions.Default(c)
   324    var count int
   325    v := session.Get("count")
   326    if v == nil {
   327      count = 0
   328    } else {
   329      count = v.(int)
   330      count++
   331    }
   332    session.Set("count", count)
   333    session.Save()
   334    c.JSON(200, gin.H{"count": count})
   335  })
   336  r.Run(":8000")
   337}
   338```
   339
   340### memstore
   341
   342```go
   343package main
   344
   345import (
   346  "github.com/gin-contrib/sessions"
   347  "github.com/gin-contrib/sessions/memstore"
   348  "github.com/gin-gonic/gin"
   349)
   350
   351func main() {
   352  r := gin.Default()
   353  store := memstore.NewStore([]byte("secret"))
   354  r.Use(sessions.Sessions("mysession", store))
   355
   356  r.GET("/incr", func(c *gin.Context) {
   357    session := sessions.Default(c)
   358    var count int
   359    v := session.Get("count")
   360    if v == nil {
   361      count = 0
   362    } else {
   363      count = v.(int)
   364      count++
   365    }
   366    session.Set("count", count)
   367    session.Save()
   368    c.JSON(200, gin.H{"count": count})
   369  })
   370  r.Run(":8000")
   371}
   372```
   373
   374### GoRM
   375
   376[embedmd]:# (_example/gorm/main.go go)
   377```go
   378package main
   379
   380import (
   381  "github.com/gin-contrib/sessions"
   382  gormsessions "github.com/gin-contrib/sessions/gorm"
   383  "github.com/gin-gonic/gin"
   384  "gorm.io/driver/sqlite"
   385  "gorm.io/gorm"
   386)
   387
   388func main() {
   389  db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
   390  if err != nil {
   391    panic(err)
   392  }
   393  store := gormsessions.NewStore(db, true, []byte("secret"))
   394
   395  r := gin.Default()
   396  r.Use(sessions.Sessions("mysession", store))
   397
   398  r.GET("/incr", func(c *gin.Context) {
   399    session := sessions.Default(c)
   400    var count int
   401    v := session.Get("count")
   402    if v == nil {
   403      count = 0
   404    } else {
   405      count = v.(int)
   406      count++
   407    }
   408    session.Set("count", count)
   409    session.Save()
   410    c.JSON(200, gin.H{"count": count})
   411  })
   412  r.Run(":8000")
   413}
   414```
   415
   416### PostgreSQL
   417
   418```go
   419package main
   420
   421import (
   422  "database/sql"
   423  "github.com/gin-contrib/sessions"
   424  "github.com/gin-contrib/sessions/postgres"
   425  "github.com/gin-gonic/gin"
   426)
   427
   428func main() {
   429  r := gin.Default()
   430  db, err := sql.Open("postgres", "postgresql://username:password@localhost:5432/database")
   431  if err != nil {
   432    // handle err
   433  }
   434
   435  store, err := postgres.NewStore(db, []byte("secret"))
   436  if err != nil {
   437    // handle err
   438  }
   439
   440  r.Use(sessions.Sessions("mysession", store))
   441
   442  r.GET("/incr", func(c *gin.Context) {
   443    session := sessions.Default(c)
   444    var count int
   445    v := session.Get("count")
   446    if v == nil {
   447      count = 0
   448    } else {
   449      count = v.(int)
   450      count++
   451    }
   452    session.Set("count", count)
   453    session.Save()
   454    c.JSON(200, gin.H{"count": count})
   455  })
   456  r.Run(":8000")
   457}
   458```

View as plain text