219 字
1 分钟
会话管理
func main() {
r := gin.Default()
r.GET("/cookie/set", func(c *gin.Context) {
c.SetCookie(
"session_id", // name
"abc123", // value
3600, // maxAge (秒)
"/", // path
"localhost", // domain
false, // secure
true, // httpOnly
)
c.JSON(http.StatusOK, gin.H{"message": "Cookie set"})
})
r.GET("/cookie/get", func(c *gin.Context) {
sessionID, err := c.Cookie("session_id")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": "Cookie not found",
})
return
}
c.JSON(http.StatusOK, gin.H{"session_id": sessionID})
})
r.GET("/cookie/delete", func(c *gin.Context) {
c.SetCookie("session_id", "", -1, "/", "localhost", false, true)
c.JSON(http.StatusOK, gin.H{"message": "Cookie deleted"})
})
r.Run(":8080")
}

Session#

import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
)
func main() {
r := gin.Default()
// 创建 cookie store
store := cookie.NewStore([]byte("secret-key"))
r.Use(sessions.Sessions("mysession", store))
r.POST("/login", func(c *gin.Context) {
session := sessions.Default(c)
var loginForm struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
if err := c.ShouldBindJSON(&loginForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 验证用户(示例)
if loginForm.Username == "admin" && loginForm.Password == "password" {
session.Set("user_id", 1)
session.Set("username", loginForm.Username)
session.Save()
c.JSON(http.StatusOK, gin.H{"message": "Login successful"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
}
})
r.GET("/profile", func(c *gin.Context) {
session := sessions.Default(c)
userID := session.Get("user_id")
if userID == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Not logged in"})
return
}
username := session.Get("username")
c.JSON(http.StatusOK, gin.H{
"user_id": userID,
"username": username,
})
})
r.POST("/logout", func(c *gin.Context) {
session := sessions.Default(c)
session.Clear()
session.Save()
c.JSON(http.StatusOK, gin.H{"message": "Logged out"})
})
r.Run(":8080")
}
会话管理
https://shirone.mysqil.com/posts/gin/会话管理/
作者
HikariTish
发布于
2026-07-18
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类

换条路线

从其他文章中稳定抽取