我正在尝试在HTML页面上设置cookie
func testCookie(c *gin.Context) {
c.SetCookie("test1", "testvalue", 10, "/", "", true, true)
c.HTML(200, "dashboard", gin.H{
"title": "Dashboard",
}
}
这应该在HTML页面上设置cookie,但事实并非如此。我的服务器正在运行以提供https请求。我不知道为什么我不能在这里设置cookie。
SetCookie()
在ResponseWriter
的标题上设置cookie,因此您可以在后续请求中读取其值,可以使用Request
对象的Cookie()
方法读取它。
这是同样的related code给你一个想法:
func (c *Context) SetCookie(
name string,
value string,
maxAge int,
path string,
domain string,
secure bool,
httpOnly bool,
) {
if path == "" {
path = "/"
}
http.SetCookie(c.Writer, &http.Cookie{
Name: name,
Value: url.QueryEscape(value),
MaxAge: maxAge,
Path: path,
Domain: domain,
Secure: secure,
HttpOnly: httpOnly,
})
}
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
}
您将无法访问页面中的cookie,因为您正在通过HttpOnly
as true
。当此设置为true时,只有服务器可以访问cookie,并且您无法使用Javascript在前端获取其值。
添加到上面的评论尝试使用
c.SetCookie("cookieName", "name", 10, "/", "yourDomain", true, true)
例
c.SetCookie("gin_cookie", "someName", 60*60*24, "/", "google.com", true, true)