package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 权限控制,局部中间件
func Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 获取客户端的cookie并进行校验
if cookie, err := c.Cookie("user_cookie"); err == nil {
if cookie == "usermosson" {
c.Next() // ?
return
}
}
c.JSON(http.StatusUnauthorized, gin.H{"error": "StatusUnauthorized"})
// 若验证不通过,则不再调用后续的处理函数
c.Abort()
return
}
}
func main() {
router := gin.Default()
// 登陆请求
router.GET("/login", func(c *gin.Context) {
// 设置cookie
//c.SetCookie("username", "mosson", 60, "/", "localhost", false, true)
c.SetCookie("user_cookie", "usermosson", 1000, "/", "localhost", false, true)
c.String(http.StatusOK, "login success")
})
// home 请求
router.GET("/home", Middleware(), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": "home"})
})
_ = router.Run(":8001")
}
// 问题描述,设置cookie不成功,各位小伙伴有时间的麻烦看一下哦!
有疑问加站长微信联系(非本文作者)