package main import ( "github.com/gin-gonic/gin" "net/http" ) //设置两个路由login和home //home查看访问信息 //login会设置cookie func checkCookie(c *gin.Context) { cookie, err := c.Cookie("login") if err != nil || cookie != "true" { c.JSON(http.StatusForbidden, gin.H{"error": http.StatusText(http.StatusForbidden)}) //如果校验不通过,就结束后续的请求 c.Abort() return } c.Next() return } func main() { r := gin.Default() { r.GET("/login", func(c *gin.Context) { c.SetCookie("login", "true", 60, "/", "localhost", false, true) c.String(http.StatusOK, "login success!") }) r.GET("/home", checkCookie, func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"data": "home"}) }) } r.Run(":8000") }