gin开发中踩过的坑
洪笳淏 Lv4

gin框架操作Cookie

坑:c.SetCookie 中的的 domain 定义成什么就要用什么访问 cookie 才会生效,例如,定义的 127.0.0.1,浏览器访问时也必须输入 127.0.0.1 才行,localhost 都不行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import (
"fmt"

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

func main() {
router := gin.Default()
router.GET("/cookie", func(c *gin.Context) {
cookie, err := c.Cookie("gin_cookie") // 获取Cookie
if err != nil {
cookie = "NotSet"
// 给客户端设置Cookie,maxAge:3600秒后过期,
// path:cookie/为Cookie所在目录,
// domain stinrg:域名
// secure:是否只能通过https访问
// httpOnly bool:是否允许别人通过js获取自己的cookie
c.SetCookie("gin_cookie", "test", 3600, "/", "127.0.0.1", false, true)
}
fmt.Printf("Cookie value: %s \n", cookie)
})

router.Run(":8080")
}
  • Post title:gin开发中踩过的坑
  • Post author:洪笳淏
  • Create time:2021-12-13 12:46:00
  • Post link:https://jiahaohong1997.github.io/2021/12/13/gin开发中踩过的坑/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments