`
qq466862016
  • 浏览: 128666 次
  • 来自: 杭州
社区版块
存档分类
最新评论

golang 集成 sessions 使用注意事项

阅读更多

    golang 集成 sessions 使用注意事项

除go基本类型外,复杂对象结构存储,必须先注册

比如我们使用如下

$ go get github.com/tommy351/gin-sessions
package routers

import (
       "github.com/gin-gonic/gin"

       "github.com/tommy351/gin-sessions"
       "blog/models"
       "fmt"
)

func init() {

       router := gin.Default()

       //设置静态资源
router.Static("/statics","./assets/statics")

       //设置模板路径
router.LoadHTMLGlob("templates/**")

       //设置session midddleware
store := sessions.NewCookieStore([]byte("dongtian_go_session"))
       router.Use(sessions.Middleware("go_dongtian_sesion",store))


       router.GET("/ping", func(c *gin.Context) {
              c.JSON(200, gin.H{
                     "message": "pong",
              })

       })

       router.GET("/set", func(c *gin.Context) {

              session := sessions.Get(c)
              user := models.User{}
              user.Id = 100
user.UserName = "冬天"
session.Set("user",user)
              session.Save()
              c.JSON(200, gin.H{
                     "message": "set",
              })
       })

       router.GET("/get", func(c *gin.Context) {

              session := sessions.Get(c)

              user := session.Get("user")
              fmt.Println("user  =",user)
              c.JSON(200, gin.H{
                     "message": "get",
              })
       })
       router.Run(":8080")
}
models 下的User
package models

import (
       "time"
       "encoding/gob"
)

type User struct {
       Id            int    `xorm:"pk"`
UserName      string `xorm:"char(32)"`
Password      string `xorm:"char(32)"`
NickName      string `xorm:"char(32)"`
NetName       string `xorm:"char(32)"`
Job           string `xorm:"char(32)"`
Address       string `xorm:"varchar(255)"`
Mobile        string `xorm:"char(32)"`
Email         string `xorm:"char(32)"`
State         int
       RegIp         string
       LastLoginIp   string
       CreateTime    time.Time `xorm:"index(index_user_create_time)","created"`
UpdateTime    time.Time `xorm:"index(index_user_update_time)","updated"`
LastLoginTime time.Time `xorm:"index(index_user_last_login_time)"`
}


func init(){
     //必须encoding/gob编码解码进行注册 
       gob.Register(&User{})
}
2
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics