Wednesday, 30 July 2025

GO LANG GORILLA SESSION

 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

  • Initialization of CookieStore:
    You initialize a CookieStore by providing a secret key. This key is crucial for authenticating and encrypting session data stored in the cookie, ensuring its integrity and preventing tampering.
  • Session Retrieval/Creation:
    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.
  • Data Storage:
    You can then store data within the session.Values map, which is a map[interface{}]interface{}This map holds the key-value pairs representing your session data.
  • Saving the Session:
    Crucially, you call session.Save(r, w) (or store.Save(r, w, session)) before writing any other content to the http.ResponseWriterThis method serializes the session data (including the session.Values), encrypts it using the secret key, and then sets the Set-Cookie HTTP header in the response.
  • Browser Action:
    When the browser receives the Set-Cookie header in the HTTP response, it stores the cookie containing the session ID and the encrypted session data.
  • Subsequent Requests:
    On subsequent requests to the same domain, the browser automatically includes this cookie in the Cookie HTTP header of the request, allowing gorilla/sessions on 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