Gorilla Sessions Tutorial confusion

272 views
Skip to first unread message

hahalau...@gmail.com

unread,
Mar 22, 2015, 1:08:52 PM3/22/15
to golan...@googlegroups.com
Hello! So I went through the Gorilla Sessions tutorial and made a Handler function, but I couldnt find many resources that teaches you how to actually use  the function. 

Specifically, for the struct thats supposed to implement the ResponseWriter interface.... are you supposed to make your own to plug in? Or are you supposed to use an existing one. I just want to be able to test the ability to log a user into a session. 

Here's my code:
https://github.com/amy/go-http-auth/blob/master/Auth/Session.go

Here's the Gorilla turtorial

Matt Silverlock

unread,
Mar 22, 2015, 7:39:55 PM3/22/15
to golan...@googlegroups.com, hahalau...@gmail.com
It's not entirely clear what you're trying to do. This function signature (type)

func StartSession(response http.ResponseWriter, request *http.Request, user User) *sessions.Session

... doesn't satisfy the http.Handler interface (http://golang.org/pkg/net/http/#Handler) as-is, so you either need to do that or just lean on the http.HandlerFunc type to do it for you. For the most part, you can just drop the session code into your existing handlers. If you want to get fancy and have separate functions (middleware) that do this for you, you'll need to write code that: a) creates the session; b) passes it to the handler via a request context; and c) saves the session before any handler writes to the http.ResponseWriter.

The "simplest" way is to just write http.HandlerFuncs.

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func HelloHandler(w http.ResponseWriter, r *http.Request) {
// Get the session; noting that "Get" creates a new session if none exists yet
sess, err := store.Get(r, "my-app-name")
if err != nil {
http.Error(w, "No good", http.StatusInternalServerError)
return
}
// do things - parse POST form values, fetch the user details from a database, etc.
// user := User{Name: someDBResult, Email: someOtherDBResult}
session.Values["user"] = user
// Save the session
err := sess.Save(r, w)
if err != nil {
http.Error(w, "No good", http.StatusInternalServerError)
return
}
// Write to the http.ResponseWriter - whether it be a template, JSON response, etc.\
}

If you want to get beyond that, you'll need to look at either creating custom handler types (so you can pass the session around), or using a request context to do so by passing the initialised session to the handler.

If I've misunderstood what you're trying to do, hash out some steps in a list starting from when the request comes in so it's clearer.
Reply all
Reply to author
Forward
0 new messages