[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")
}
}

posted on   进击的davis  阅读(608)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?

导航

< 2025年3月 >
23 24 25 26 27 28 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
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示