在渲染HTML页面之前设置go-gin。

huangapple go评论89阅读模式
英文:

Setting before rendering html page go-gin

问题

我正在尝试在一个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。我正在使用Google Chrome浏览器,理论上我应该能够在那里看到cookie。

英文:

I am trying to set a cookie on an HTML page

 func testCookie(c *gin.Context) {
    c.SetCookie("test1", "testvalue", 10, "/", "", true, true)
	c.HTML(200, "dashboard", gin.H{
		"title":    "Dashboard",
        }
    }

This should have set the cookie on the HTML page but it doesn't.
My server is running to serve https requests. I am not sure why I am not able to set cookies here. I am using google-chrome and ideally I should have been able to see the cookie there.

答案1

得分: 2

问题出在你的maxAge输入上。你当前的代码指示浏览器在10秒钟内删除你的cookie。

Gin正在封装http.SetCookie,并为你创建一个http.Cookie。为了更好地理解发生了什么,你应该阅读这两个链接。

> MaxAge=0表示没有指定'Max-Age'属性。
>
> MaxAge<0表示立即删除cookie,相当于'Max-Age: 0'
>
> MaxAge>0表示'Max-Age'属性存在,并以秒为单位给出。

英文:

The issue is with your maxAge input. Your current code instructs the browser to delete your cookie in 10 seconds.

Gin is wrapping http.SetCookie and creating a http.Cookie for you. To better understand what is happening you should read through those two links.

> MaxAge=0 means no 'Max-Age' attribute specified.
>
> MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
>
> MaxAge>0 means Max-Age attribute present and given in seconds

huangapple
  • 本文由 发表于 2016年12月1日 01:21:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40894443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定