2
votes

I'm using Gorilla to enable session variables on Google App Engine. So far I imported "github.com/gorilla/sessions" only, but Gorilla's page says:

If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))

My question is how do I adapt this for the App Engine Standard Environment, which as far as I know does not use http.ListenAndServe by default. My code looks like this:

package test

import (
    "fmt"
    "net/http"
    "github.com/gorilla/sessions"   
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {

    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"])

}

Would I get a memory leak this way?

2

2 Answers

2
votes

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"])
}
1
votes

Gorilla also offers a context.Clear() option that you can put in your request handler as per the docs here:

https://godoc.org/github.com/gorilla/context#Clear

So your handler func would become:

func handler(w http.ResponseWriter, r *http.Request) {

    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"])
    context.Clear(r)
}