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()
}
■ ■■■■
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()
}