The doc you quoted tells everything you need to do: wrap your handlers using context.ClearHandler()
. Since you "only" have a handler function and not an http.Handler
, you may use the http.HandlerFunc
adapter to get a value that implements http.Handler
:
func init() {
http.Handle("/", context.ClearHandler(http.HandlerFunc(handler)))
}
You need to do this for every handler you register. That's why the doc mentions that it's easier to just wrap the root handler you pass to http.ListenAndServe()
(and that way you don't have to wrap the other, non-top-level handlers). But this isn't the only way, just the easiest / shortest.
If you don't call http.ListenAndServe()
yourself (as in App Engine), or you don't have a single root handler, then you need to wrap all handlers manually that you register.
Note that the handler returned by context.ClearHandler()
does nothing magical, all it does is call context.Clear()
after calling the handler you pass. So you may just as easily call context.Clear()
in your handler to achieve the same effect.
If you do so, one important thing is to use defer
as if for some reason context.Clear()
would not be reached (e.g. a preceding return
statement is encountered), you would again leak memory. Deferred functions are called even if your function panics. So it should be done like this:
func handler(w http.ResponseWriter, r *http.Request) {
defer context.Clear(r)
var cookiestore = sessions.NewCookieStore([]byte("somesecret"))
session, _ := cookiestore.Get(r, "session")
session.Values["foo"] = "bar"
fmt.Fprintf(w, "session value is %v", session.Values["foo"])
}
Also note that the session store creation should only be done once, so move that out from your handler to a global variable. And do check and handle errors to save you some headache. So the final suggested code is this:
package test
import (
"fmt"
"net/http"
"log"
"github.com/gorilla/context"
"github.com/gorilla/sessions"
)
func init() {
http.Handle("/", context.ClearHandler(http.HandlerFunc(handler)))
}
var cookiestore = sessions.NewCookieStore([]byte("somesecret"))
func handler(w http.ResponseWriter, r *http.Request) {
session, err := cookiestore.Get(r, "session")
if err != nil {
// Handle error:
log.Printf("Error getting session: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session.Values["foo"] = "bar"
fmt.Fprintf(w, "session value is %v", session.Values["foo"])
}