- 不知道为什么用gin.Context的SetCookie方法设置不到cookie,有待研究
- 一位伟大的网友记录的方法,学习一下
- 参考链接
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
func main() {
r := gin.Default()
r.Use(cookieCheck())
r.GET("/http_cookie", func(c *gin.Context) {
if cookie, err := c.Request.Cookie("cookie"); err == nil {
fmt.Println("http cookie")
c.String(http.StatusOK, cookie.Value)
}
})
r.Run(":8080")
}
func cookieCheck() gin.HandlerFunc {
return func(c *gin.Context) {
if cookie, err := c.Request.Cookie("cookie"); err == nil {
value := cookie.Value
if v, err := strconv.Atoi(value); err == nil {
i := v + 1
cookie.Value = fmt.Sprintf("%d", i)
}
http.SetCookie(c.Writer, cookie)
c.Next()
} else {
cookie := &http.Cookie{
Name: "cookie",
Value: "0",
}
http.SetCookie(c.Writer, cookie)
}
}
}