lauantai 21. helmikuuta 2015

Setting a cookie with Golang

Couldn't find a good example about how to set a cookie to response with Golang using Gin.

So, here is what I did

r.LoadHTMLTemplates("templates/*")
r.GET("/en", func(c *gin.Context)
 
{
    expire
 
:=
 time
.Now
().AddDate
(
1
,
 
0
,
 
1
)
    cookie
 :=
 http.Cookie
{"cookieName", "cookieValue",
        "/", ".domain.com", expire, expire.Format(time.UnixDate), 
        41472000, false, false, "cookieName=cookieValue", 
        []string{"cookieName=cookieValue"}}
     http.SetCookie(context.Writer, &cookie)
     c.HTML(200, "index.html", gin.H{"title""Main website"})
})


From documentation (http://golang.org/src/net/http/cookie.go)

type Cookie struct { 
    Name string 
    Value string 
    Path string 
    Domain string 
    Expires time.Time 
    RawExpires string 
    // 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 
    MaxAge int 
    Secure bool 
    HttpOnly bool 
    Raw string 
    Unparsed []string // Raw text of unparsed attribute-value pairs 
}