-
-
Save pmkhoa/5b97f36ac26172216851750958ee2c54 to your computer and use it in GitHub Desktop.
Golang - Making julienschmidt/httprouter compatible using gorilla/context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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