Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Last active April 13, 2017 16:08
Show Gist options
  • Save josephspurrier/7a6f608c2bf8d95f3dd2 to your computer and use it in GitHub Desktop.
Save josephspurrier/7a6f608c2bf8d95f3dd2 to your computer and use it in GitHub Desktop.
Golang - Making julienschmidt/httprouter compatible using gorilla/context
// Source: http://nicolasmerouze.com/guide-routers-golang/
// Package httprouterwrapper allows the use of http.HandlerFunc compatible funcs with julienschmidt/httprouter
package httprouterwrapper
import (
"net/http"
"github.com/gorilla/context"
"github.com/julienschmidt/httprouter"
)
// Simple accepts the name of a function so you don't have to wrap it with http.HandlerFunc
// Example: r.GET("/", httprouterwrapper.Simple(controller.Index))
func Simple(h http.HandlerFunc) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
context.Set(r, "params", p)
h.ServeHTTP(w, r)
}
}
// Compatible accepts a handler to make it compatible with http.HandlerFunc
// Example: r.GET("/", httprouterwrapper.Compatible(http.HandlerFunc(controller.Index)))
func Compatible(h http.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
context.Set(r, "params", p)
h.ServeHTTP(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment