4

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.

codec
  • 7,978
  • 26
  • 71
  • 127

2 Answers2

4

Adding to comments above Try using

c.SetCookie("cookieName", "name", 10, "/", "yourDomain", true, true)

example

c.SetCookie("gin_cookie", "someName", 60*60*24, "/", "google.com", true, true)
Mendo
  • 319
  • 2
  • 7
1

SetCookie() sets the cookie on the ResponseWriter's headers hence you can read its value in subsequent requests where it can be read using Request object's Cookie() method.

Here's the related code of the same to give you an idea:

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
}

Update

You won't be able to access cookies in your page because you're passing HttpOnly as true. When this is set to true only the server has access to the cookies and you can't fetch their values in front-end using Javascript.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • `c.SetCookie("test1", "testvalue", 10, "/", "", true, true) c.HTML(200, "dashboard", gin.H{ "title": "Dashboard", }` This should have ideally set the cookie on the HTML page but its not working – codec Nov 30 '16 at 17:12
  • @love2code What do you mean by it should set in HTML page? A cookie is part of the headers. Considering you're passing HttpOnly as True you won't be able to access the cookie using Javascript either. – Ashwini Chaudhary Dec 01 '16 at 04:35
  • @love2code Read more about HttpOnly cookie here: https://www.owasp.org/index.php/HttpOnly – Ashwini Chaudhary Dec 01 '16 at 09:48