gin中提供了session包用于處理session
我們可以把session放在cookie问词,Redis督函,Memcached,MongoDB里面激挪,具體可以查看github上的示例辰狡。
有時(shí)候我們?yōu)榱藵M足我們的業(yè)務(wù)需求,需要把一個(gè)struct存入session怎么辦呢垄分?
package main
import (
"encoding/gob"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
"movie/app/http/controller/api"
"movie/app/http/middleware"
"movie/app/model"
"time"
)
func main() {
//首先要注冊(cè)User模型
gob.Register(model.User{})
router := gin.Default()
store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
store.Options(sessions.Options{
MaxAge: int(30 * time.Minute), //30min
Path: "/",
})
router.Use(sessions.Sessions("movie", store))
router.GET("/movie/index", api.Index)
router.GET("/movie/user", api.User)
_ = router.Run(":8081")
}
定義user模型
package model
type User struct {
Name string `json:"name"`
Password string `json:"password"`
Mobile string `json:"mobile"`
}
在controller層存取域名
/*
@Author : 寒云
@Email : 1355081829@qq.com
@Time : 2019/12/18 14:13
*/
package api
import (
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"movie/app/model"
)
func Index(c *gin.Context) {
session := sessions.Default(c)
// 把User放進(jìn)session里面
session.Set("session_01", model.User{Name: "hanyun"})
_ = session.Save()
}
func User(c *gin.Context) {
session := sessions.Default(c)
value := session.Get("session_01")
fmt.Println(value)
}
1宛篇、我們?cè)趍ain方法里把需要放進(jìn)session的模型注冊(cè)進(jìn)來(lái)
gob.Register(model.User{})
2、把路由/movie/index中把模型放在session里面
3薄湿、在路由/movie/user里從session里取出模型
最終解決session跨頁(yè)面存取模型