我正在尝试在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。
发布于 2019-04-08 19:23:03
添加到上面的注释尝试使用
c.SetCookie("cookieName", "name", 10, "/", "yourDomain", true, true)示例
c.SetCookie("gin_cookie", "someName", 60*60*24, "/", "google.com", true, true)发布于 2016-11-30 20:13:55
SetCookie()在ResponseWriter的头上设置cookie,因此您可以在后续请求中读取它的值,可以使用Request对象的Cookie()方法读取它。
下面是same的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
}更新
您将无法访问页面中的cookies,因为您正在传递HttpOnly as true。当它设置为true时,只有服务器有权访问cookie,并且您不能使用Javascript在前端获取它们的值。
https://stackoverflow.com/questions/40887538
复制相似问题