gin框架30--设置和获取 Cookie

介绍

本文主要介绍如何在gin框架中设置和获取 Cookie,并加以案例说明。

案例

源码:

package main

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

func main() {
r := gin.Default()
r.GET("/cookie", func(c *gin.Context) {
cookie, err := c.Cookie("gin_cookie")
if err != nil {
cookie = "NotSet"
c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
}
fmt.Printf("Cookie value: %s, %s \n", cookie, err)
})
r.Run(":8080")
}

测试:

$ curl -v http://127.0.0.1:8080/cookie
* Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> GET /cookie HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/7.74.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Set-Cookie: gin_cookie=test; Path=/; Domain=localhost; Max-Age=3600; HttpOnly
< Date: Sat, 02 Apr 2022 16:04:00 GMT
< Content-Length: 0
<
* Connection #0 to host 127.0.0.1 left intact

终端输出:
[GIN-debug] Listening and serving HTTP on :8080
Cookie value: NotSet, http: named cookie not present
[GIN] 2022/04/03 - 00:04:00 | 200 | 25.569µs | 127.0.0.1 | GET "/cookie"

说明

​gin框官方文档 设置和获取 Cookie​