[go-每日一库]golang gin框架的session的简单实现
主要思路:
- 1.通过cookie作为载体,实例化store
- 2.设置超时时间
- 3.注册session的中间件
- 4.业务逻辑判断后设置session的key-value,并生成session
代码如下:
点击查看代码
package main
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"net/http"
)
type User struct {
Id int `json:"id"`
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
// as cmd, server main
func main() {
r := router()
r.Run(":8080")
}
// split to router
func router() *gin.Engine {
// if set release-mode, there is no debug info
//gin.SetMode(gin.ReleaseMode)
// new a engine
r := gin.Default()
// create new store, cookie as the carrier
store := cookie.NewStore([]byte("secret"))
// set timeout, unit is second
store.Options(sessions.Options{MaxAge: 60*60, Path: "/"})
// register middleware, key as cookie name
r.Use(sessions.Sessions("sessionid", store))
// register router
r.POST("/login", login)
return r
}
// split to service
func login(c *gin.Context) {
var user User
if c.ShouldBindJSON(&user) != nil {
c.String(http.StatusOK, "params error")
return
}
// get session from request
getSession, _ := c.Cookie("sessionid")
fmt.Println(getSession)
if user.Username == "username" && user.Password == "password" {
session := sessions.Default(c)
//sessionid := session.Get("hello")
//if sessionid == nil {
// fmt.Println("sessionid is nil")
//}
// set session key-value
session.Set("hello", "world")
// generate session
session.Save()
// return string
//c.String(http.StatusOK, "login success")
// return json obj
c.JSON(http.StatusOK, gin.H{
"msg": "login success",
})
} else {
c.String(http.StatusOK, "login fail")
}
}