Get session values ​​in golang

My rails application uses a session to store user credentials for authorization. An attempt to log into the system and perform some actions (requiring a user session) in the Go code. Should I get a user session on login and move on to the next request? How can I handle this?

+6
source share
1 answer
Standard library

Go does not provide an HTTP session manager. Thus, you must write one or use one written by others.

Some examples:

Typically, HTTP sessions are managed using cookies between the server and the client, and therefore the session (session ID) can be obtained directly from the request ( http.Request ), for example with Request.Cookie() .

There is no need to "pass" the session through the "request chain", each handler can access it only using http.Request .

For example, using github.com/icza/session , this can be done as follows:

 func MyHandler(w http.ResponseWriter, r *http.Request) { sess := session.Get(r) if sess == nil { // No session (yet) } else { // We have a session, use it } } 

Using Gorilla sessions seems to be:

 var store = sessions.NewCookieStore([]byte("something-very-secret")) func MyHandler(w http.ResponseWriter, r *http.Request) { session, err := store.Get(r, "session-name") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Use session } 
+7
source

All Articles