这里附上完整代码
package main import ( "encoding/gob" "fmt" "net/http" "reflect" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" ) type Student struct { Name string Year int Major string } func main() { r := gin.Default() r.LoadHTMLGlob("templates/*") // 配置session中间件 // 创建基于cookie的存储引擎,secret是加密的密钥 store := cookie.NewStore([]byte("secret")) // store是创建的引擎,可以换成其他引擎 gob.Register([]Student{}) r.Use(sessions.Sessions("mysession", store)) r.GET("/set", func(ctx *gin.Context) { sesstion := sessions.Default(ctx) //定义一个结构体切片 list := []Student{} student1 := Student{"韩立1", 1200, "1大衍诀"} student2 := Student{"韩立2", 2200, "2大衍诀"} student3 := Student{"韩立3", 3200, "3大衍诀"} student4 := Student{"韩立4", 4200, "4大衍诀"} list = append(list, student1) list = append(list, student2) list = append(list, student3) list = append(list, student4) //str := []string{"金", "木", "水", "火"} sesstion.Set("s1", list) sesstion.Save() ctx.String(http.StatusOK, "设置session成功") }) r.GET("/get", func(ctx *gin.Context) { sesstion := sessions.Default(ctx) ss := (sesstion.Get("s1")) //利用断言强制类型转换 p, ok := (ss).(Student) if ok { fmt.Println(reflect.TypeOf(p)) } else { fmt.Println("can not convert") } fmt.Println(ss) ctx.HTML(200, "a.html", gin.H{ "ss": ss, }) }) r.Run() }
基于cookie创建的session,gob.Register([]Student{})是用来设置强制类型转换全局设置
r := gin.Default() r.LoadHTMLGlob("templates/*") // 配置session中间件 // 创建基于cookie的存储引擎,secret是加密的密钥 store := cookie.NewStore([]byte("secret")) // store是创建的引擎,可以换成其他引擎 gob.Register([]Student{})//强制类型转换的全局设置 r.Use(sessions.Sessions("mysession", store))
这里我们在set路由下存入了一个结构体切片数据
r.GET("/set", func(ctx *gin.Context) { sesstion := sessions.Default(ctx) //定义一个结构体切片 list := []Student{} student1 := Student{"韩立1", 1200, "1大衍诀"} student2 := Student{"韩立2", 2200, "2大衍诀"} student3 := Student{"韩立3", 3200, "3大衍诀"} student4 := Student{"韩立4", 4200, "4大衍诀"} list = append(list, student1) list = append(list, student2) list = append(list, student3) list = append(list, student4) sesstion.Set("s1", list) sesstion.Save() ctx.String(http.StatusOK, "设置session成功") })
然后我们在get路由下获取这个结构体切片数据,这里利用断言强制类型转换可以自行封装成函数
r.GET("/get", func(ctx *gin.Context) { sesstion := sessions.Default(ctx) ss := (sesstion.Get("s1")) //利用断言强制类型转换 p, ok := (ss).(Student) if ok { fmt.Println(reflect.TypeOf(p)) } else { fmt.Println("can not convert") } fmt.Println(ss) ctx.HTML(200, "a.html", gin.H{ "ss": ss, }) })