219 字
1 分钟
会话管理
Cookie
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")}分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 89 天
部分内容可能已过时