Is a small wrapper around gorilla/mux
with few additions:
r.HandleFunc
accepts customHandlerFunc
or you can usehttp.HandlerFunc
usingr.HandleFuncBypass
r.Use
accepts customMiddlewareFunc
or you can usefunc(http.Handler) http.Handler
usingr.UseBypass
NewRouter()
acceptsOptions
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
Example:
func userHandler(w http.ResponseWriter, r *http.Request) error {
id := mux.Vars(r)["id"]
user, err := loadUser(id)
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, user)
}
r := mux.NewRouter()
r.HandleFunc("/", userHandler)
type MiddlewareFunc func(w http.ResponseWriter, r *http.Request) (context.Context, error)
Example:
func authMiddleware(w http.ResponseWriter, r *http.Request) (context.Context, error) {
sess, err := store.Session(r)
if err != nil {
return nil, httpError(http.StatusUnauthorized, "Unauthorized")
}
id, err := sess.Value(userIDKey)
if err != nil {
return nil, httpError(http.StatusUnauthorized, "Unauthorized")
}
return context.WithValue(r.Context(), userIDContextKey, id)
}
r := mux.NewRouter()
r.Use(authMiddleware)
r.HandleFunc("/me", meHandler)
With custom error handler:
func withCustomErrorHandler(r *mux.Router) {
r.ErrorHandlerFunc = func(err error, w http.ResponseWriter, r *http.Request) {
switch e := err.(type) {
case *HTTPError:
sendJSON(w, e.Code, e)
break
case *database.Error:
http.Error(w, e.Message, http.StatusInternalServerError)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
break
}
}
}
r := mux.NewRouter(withCustomErrorHandler)
With custom not found handler:
func withNotFound(r *mux.Router) {
r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) error {
// some stuff...
http.Error(w, "Not Found", http.StatusNotFound)
return nil
}
}
r := mux.NewRouter(withNotFound)
With custom method not allowed handler:
func withMethodNotAllowed(r *mux.Router) {
r.MethodNotAllowedHandler = func(w http.ResponseWriter, r *http.Request) error {
// some stuff...
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return nil
}
}
r := mux.NewRouter(withMethodNotAllowed)