本篇文章說明 gin-contrib/sessions 的部分函式和結構

sessions.Default

shortcut to get session

1
session := sessions.Default(ctx)

sessions.Session.Get

Get returns the session value associated to the given key.

1
session.Get("isLogin")

sessions.Session.Set

Set sets the session value associated to the given key.

1
session.Set("isLogin", false)

sessions.Session.Save

Save saves all sessions used during the current request.

1
session.Save()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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("/incr", func(c *gin.Context) {
session := sessions.Default(c)
var count int
v := session.Get("count")
if v == nil {
count = 0
} else {
count = v.(int)
count++
}
session.Set("count", count)
session.Save()
c.JSON(200, gin.H{"count": count})
})
r.Run(":8000")
}