gin-contrib/session支持的存储引擎

  • cookie
  • redis

安装session包

1go get github.com/gin-gonic/contrib/session

基于cookie的session

创建cookieStore并放到gin中间件中

1func cookieSession(r *gin.Engine) {
2  store := sessions.NewCookieStore([]byte("secret"))
3  r.Use(sessions.Sessions("SESSIONID", store))
4}

main.go函数调用cookieSession

 1func main() {
 2  r := gin.Default()
 3  cookieSession(r)
 4  r.GET("/login", func(ctx *gin.Context) {
 5    user := ctx.Query("user")
 6    if user == "" {
 7      ctx.String(http.StatusOK, "登录失败")
 8      return
 9    }
10    session := sessions.Default(ctx)
11    session.Set("user", user)
12    session.Save()
13    ctx.String(http.StatusOK, user+"登录成功")
14  })
15
16  r.GET("/user", func(ctx *gin.Context) {
17    session := sessions.Default(ctx)
18    if user := session.Get("user"); user != nil {
19      ctx.String(http.StatusOK, user.(string))
20      return
21    } else {
22      ctx.String(http.StatusOK, "未登录")
23    }
24  })
25  r.Run()
26}

运行

1go run main.go

测试

 1curl -v http://localhost:8080/login?user=jerry
 2*   Trying ::1...
 3* TCP_NODELAY set
 4* Connected to localhost (::1) port 8080 (#0)
 5> GET /login?user=jerry HTTP/1.1
 6> Host: localhost:8080
 7> User-Agent: curl/7.64.1
 8> Accept: */*
 9>
10< HTTP/1.1 200 OK
11< Content-Type: text/plain; charset=utf-8
12< Set-Cookie: SESSIONID=MTYyNTExMTIyOHxOd3dBTkZSUlFWTTNSREpaVjBnME56VldNMUZEVDBzMVFsTlJTbGxRVTBVM1FqVklRVTFGVlVwUFZrWktWRXd6U1RWUFdFaE1OVUU9fHCREaED012ScD-K4fqZyikS5qZNyXDpwkc8ZD-aZqVk; Path=/; Expires=Sat, 31 Jul 2021 03:47:08 GMT; Max-Age=2592000
13< Date: Thu, 01 Jul 2021 03:47:08 GMT
14< Content-Length: 17
15<
16* Connection #0 to host localhost left intact
17jerry登录成功* Closing connection 0
18
19curl -v --cookie "SESSIONID=MTYyNTExMTIyOHxOd3dBTkZSUlFWTTNSREpaVjBnME56VldNMUZEVDBzMVFsTlJTbGxRVTBVM1FqVklRVTFGVlVwUFZrWktWRXd6U1RWUFdFaE1OVUU9fHCREaED012ScD-K4fqZyikS5qZNyXDpwkc8ZD-aZqVk" http://localhost:8080/user
20*   Trying ::1...
21* TCP_NODELAY set
22* Connected to localhost (::1) port 8080 (#0)
23> GET /user HTTP/1.1
24> Host: localhost:8080
25> User-Agent: curl/7.64.1
26> Accept: */*
27> Cookie: SESSIONID=MTYyNTExMTIyOHxOd3dBTkZSUlFWTTNSREpaVjBnME56VldNMUZEVDBzMVFsTlJTbGxRVTBVM1FqVklRVTFGVlVwUFZrWktWRXd6U1RWUFdFaE1OVUU9fHCREaED012ScD-K4fqZyikS5qZNyXDpwkc8ZD-aZqVk
28>
29< HTTP/1.1 200 OK
30< Content-Type: text/plain; charset=utf-8
31< Date: Thu, 01 Jul 2021 03:47:40 GMT
32< Content-Length: 5
33<
34* Connection #0 to host localhost left intact
35jerry* Closing connection 0

已经拿到用户相关信息了。 备注:使用curl进行请求的时候,需要携带上cookie参数

基于redis存储引擎的session

创建redisSession并放到gin中间件中

1func redisSession(r *gin.Engine) {
2  store, err := sessions.NewRedisStore(10, "tcp", "127.0.0.1:6379", "", []byte("secret"))
3  if err != nil {
4    panic(err.Error())
5  }
6  r.Use(sessions.Sessions("SESSIONID", store))
7}

cookieSession(r)替换为redisSession(r)

测试方法同cookie测试方法,也可以使用浏览器直接输入URL进行访问

gin-session