Search code examples
go

Golang gin framework cookie generating issue


This is my code and I copy it from the go-gin framework documents, My problem is when createCookie function hits it returns "NotSet" and I have to run same API callback to get a cookie.

// createCookie accepts c as gin context and create cookies
func createCookie(c *gin.Context) (string, error) {
    cookie, err := c.Cookie("device")

    if err != nil {
        cookie = "NotSet"
        c.SetCookie("device", "test", 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
    }

    return cookie, nil
}

Solution

  • // createCookie accepts c as gin context and create cookies
    func createCookie(c *gin.Context) (string, error) {
        cookie, err := c.Cookie("device")
    
        if err != nil {
            // Replae it with your initial value
            cookie = "NotSet"
            c.SetCookie("device", cookie, 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
        }
    
        return cookie, nil
    }