gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.96k stars 8.02k forks source link

SetCookie does not work #3681

Open davidh16 opened 1 year ago

davidh16 commented 1 year ago

I am trying to set a cookie, but I am not getting it nor in Postman nor in browser.

.
.
.
cookie := &http.Cookie{
        Name:     credentials.EmailAddress,
        Value:    sessionKey,
        MaxAge:   600,
        Path:     "/",
        Domain:   "localhost",
        Secure:   false,
        HttpOnly: false,
    }

http.SetCookie(ctx.Writer, cookie)

SendResponse(ctx, Response{
    Status:  http.StatusOK,
    Message: "successfully logged in",
})
return

I get a response message that I successfully logged in, but there is no cookie. To be clear this is just a part of a handler, the code before this snippet is not important since everything is working except setting the cookie.

sasidharansd commented 1 year ago

Hey @davidh16 , Alternatively you can also use gin to set and get cookie, works like a charm. Docs: https://gin-gonic.com/docs/examples/cookie/

aarontanjaya commented 1 year ago

Have you checked for error messages in the "cookie" tab of the network call in devtools?

Panici4 commented 1 year ago

i think it is because the cookie name contains invalid rune(maybe @). image

acfuns commented 1 year ago

I think you are developing locally and have a front-end back-end split, so it's easy to run into CORS problems. This is a typical CORS problem. go get github.com/gin-contrib/cors middleware to let your back-end set up cross-domains. Remember that only by adding Allowcredials: True, the browser allows you to extract data from the Set-Cookie request header. so you search cors middeware doc.

acfuns commented 1 year ago
  config := cors.DefaultConfig()
  config.AllowAllOrigins = []string{"http://localhost:3000"} // no set *
  config.Allowcredials = True
  router.Use(cors.New(config))