The gorilla/sessions package in Go handles session management, and when configured to use CookieStore, it sets a cookie in the browser to maintain session state. This process involves the following steps:
Gorilla session also creates session file in OS temp directory
https://stackoverflow.com/questions/73263370/gorilla-session-not-setting-cookie
- You initialize a
CookieStoreby providing a secret key. This key is crucial for authenticating and encrypting session data stored in the cookie, ensuring its integrity and preventing tampering. - In your HTTP handler, you call
store.Get(r, "session-name")to either retrieve an existing session associated with the incoming request or create a new one if no session with that name is found. - You can then store data within the
session.Valuesmap, which is amap[interface{}]interface{}. This map holds the key-value pairs representing your session data. - Crucially, you call
session.Save(r, w)(orstore.Save(r, w, session)) before writing any other content to thehttp.ResponseWriter. This method serializes the session data (including thesession.Values), encrypts it using the secret key, and then sets theSet-CookieHTTP header in the response. - When the browser receives the
Set-Cookieheader in the HTTP response, it stores the cookie containing the session ID and the encrypted session data. - On subsequent requests to the same domain, the browser automatically includes this cookie in the
CookieHTTP header of the request, allowinggorilla/sessionson the server to retrieve and decrypt the session data, thus maintaining the user's state across requests.
Important Note: The
MaxAge option, either set globally for the CookieStore or individually for a session's Options, determines how long the browser should retain the cookie. This MaxAge value is included in the Set-Cookie header sent to the browser.
No comments:
Post a Comment