1. Cookie简介

我们知道,HTTP协议是一种无状态的协议,这也就是说,服务端是不能够记录客户端的访问状态,换句话说,也就是服务端不能区分两次请求是否由同一个客户端发出的。而Cookie就是解决HTTP协议无状态的方案之一。

Cookie实际上就是服务器保存在浏览器上的一段信息(用于在浏览器中保存一些小数据,例如客户标识、用户非敏感数据)。浏览器有了Cookie之后,每次向服务器发送请求时都会同时将该信息发送给服务器,服务器收到请求后,就可以根据该信息处理请求。Cookie由服务器创建,并发送给浏览器,最终由浏览器保存。

■ ■■■■

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
if path == "" {
path = "/"
}
http.SetCookie(c.Writer, &http.Cookie{
Name: name,
Value: url.QueryEscape(value),
MaxAge: maxAge,
Path: path,
Domain: domain,
SameSite: c.sameSite,
Secure: secure,
HttpOnly: httpOnly,
})
}
package main


import (
  "github.com/gin-gonic/gin"
)


func main() {
  router := gin.Default()
router.GET("/set_cookie", func(c *gin.Context) {
// 设置cookie
     c.SetCookie("test_cookie", "cookie_value", 3600, "/", "localhost", false, true)
})


router.Run()
}
func (c *Context) Cookie(name string) (string, error) {
cookie, err := c.Request.Cookie(name)
if err != nil {
return "", err
}
val, _ := url.QueryUnescape(cookie.Value)
return val, nil
}
package main


import (
"github.com/gin-gonic/gin"
)


func main() {
  router := gin.Default()


router.GET("/get_cookie", func(c *gin.Context) {
    data, _ := c.Cookie("test_cookie")
c.String(200, data)
})


router.Run()
}

■ ■■■■


4. 删除cookie

您可以通过将Cookie的MaxAge设置为-1, 达到删除cookie的目的。如下示例:
package main


import (
"github.com/gin-gonic/gin"
)


func main() {
  router := gin.Default()


router.GET("/del_cookie", func(c *gin.Context) {
// 设置cookie MaxAge设置为-1,表示删除cookie
c.SetCookie("test_cookie", "cookie_value", -1, "/", "localhost", false, true)
c.String(200,"删除cookie")
})


router.Run()
}