moesef
moesef

Reputation: 4841

Get existing gorilla sessions

I am trying to set a gorilla session and then retreive the value again. I am doing the following just as a test.

//create session and store in http Cookies
session, err := store.Get(req, "session")
if err != nil {
    errCode = http.StatusInternalServerError
    return
}

//save a value
session.Values["user_id"] = userTuple.UserId
err = session.Save(req, w)
if err != nil {
    errCode = http.StatusInternalServerError
    return
}

//try to get the same session that was just created
nr := http.Request{Header: w.Header()}
session, err = store.Get(&nr, "session")
if err != nil {
    errCode = http.StatusInternalServerError
    return
} else if session.IsNew {
    log.Println("New session created instead of old one.")
}

This is a snippet out of a larger HTTP handler. But the relavent parts are posted and the the second call to store.Get() is not returning an existing session, but a brand new one. Hence, when the handler this code is in is executed, the log statements is printed to console.

Why am I getting a new session in this case instead of the one I had already created and saved?

Upvotes: 2

Views: 2166

Answers (3)

nucleartide
nucleartide

Reputation: 3988

I don't think this has anything to do with gorilla/sessions, but with how you're constructing that request struct.

When you call session.Save(r, w), w.Header() will now contain a map like the following:

map[string][]string{
  // ...
  "Set-Cookie": []string{/* ... */}
  // ...
}

You should replace that Set-Cookie header with a Cookie header - otherwise, gorilla/sessions won't see any cookies in the request, and will assume that the request didn't have a session cookie.

But yeah, like @OneOfOne mentioned, you'd usually just call http.Redirect and have the browser do that Set-Cookie-Cookie replacement for you.

Upvotes: 0

jmaloney
jmaloney

Reputation: 12280

I feel like I already answered this question. You are misusing this pkg. Behind the scenes the context package is used to store state for a request, by creating a new, incomplete http.Request, the context package returns an empty state with no session info.

check out this code to see what i'm talking about.

Upvotes: 2

OneOfOne
OneOfOne

Reputation: 99215

The following code won't work because the actual season values are saved inside the cookie that is written to ResponseWriter, copying:

nr := http.Request{Header: w.Header()}
session, err = store.Get(&nr, "session")

The code for saving is https://github.com/gorilla/sessions/blob/master/store.go#L101

And it stores season id based on the request pointer for some odd reason, check https://github.com/gorilla/context/blob/master/context.go#L31.

You'd have to reload the page to access the new cookies.

Upvotes: 1

Related Questions