Tips and Tricks

Wrap a http.HandlerFunc closure

Sometimes you want to pass data to a http.HandlerFunc on initialization. This
can easily be done by creating a closure of the http.HandlerFunc:

  1. func MyHandler(database *sql.DB) http.Handler {
  2. return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  3. // you now have access to the *sql.DB here
  4. })
  5. }

Using gorilla/context for request-specific data

It is pretty often that we need to store and retrieve data that is specific to
the current HTTP request. Use gorilla/context to map values and retrieve them
later. It contains a global mutex on a map of request objects.

  1. func MyHandler(w http.ResponseWriter, r *http.Request) {
  2. val := context.Get(r, "myKey")
  3. // returns ("bar", true)
  4. val, ok := context.GetOk(r, "myKey")
  5. // ...
  6. }