session.ID returns null string for existing sessions

379 views
Skip to first unread message

John Rinehart

unread,
Jan 3, 2016, 11:05:33 AM1/3/16
to Gorilla web toolkit
I am trying to use gorilla/sessions to monitor clients connected to my server. I am using the following code to assign an ID field to the user which is used in other parts of my application to serve as a label for the user. It's a chat application, so this ID is used as the string labelling the user in the chat history.

func getSessionInfo(req *http.Request, writer http.ResponseWriter, name string) *sessions.Session {
    session, err := sessionStore.Get(req, name)
    if err != nil {
        fmt.Println("Couldn't get session", name)
        log.Fatal(err)
    }
    if session.IsNew {
        session.ID = genRandomID(10) // 10 character random string
    }

    fmt.Println("ID:", session.ID, "; Values:", session.Values,
        "; Options:", session.Options, "; IsNew:", session.IsNew)

    // Save the session information
    session.Save(req, writer)

    return session
}

I run this function each time I received an HTTP request. This function works well and assigns an ID to the user for their first request. However, for all additional requests after the initial request (that is, for requests where session.IsNew returns false) the ID field is null. It is not being preserved during the duration of the session. I don't know why this is the case. I have worked around this, for now, by doing the following:

session.ID = genRandomID(10)  -> session.Values["userID"] = genRandomID(10)

I guess I don't know what ID means and how it's state is changed. Can I get some help with this? Thank you.

Matt Silverlock

unread,
Jan 3, 2016, 11:16:46 AM1/3/16
to Gorilla web toolkit
session.ID is a bit of an oddity in the API—it's best to avoid it. Some stores use it and encode it, and others—like the CookieStore—don't. The CookieStore doesn't encode it when calling Save() - https://github.com/gorilla/sessions/blob/b6bcae186ac3099dba8fafce125dc930393f1e5e/store.go#L107-L108

The proper way to store values in the session is via `sessions.Values`.

I didn't author the original API but I'll update the docs to clarify that session.ID is primarily for store authors writing server-side stores - boj/redistore uses it to store an ID as server-side stores don't have 'values' - https://github.com/boj/redistore/blob/9c0e6bab4dd444285424f189b8fb0cb03f653242/redistore.go#L264-L267

John Rinehart

unread,
Jan 3, 2016, 7:27:35 PM1/3/16
to Gorilla web toolkit
Oh, okay. Thanks, Matt. I'll encode that data into sessions.Values.
Reply all
Reply to author
Forward
0 new messages