Is a small wrapper around gorilla/mux with few additions:
r.HandleFuncaccepts customHandlerFuncor you can usehttp.HandlerFuncusingr.HandleFuncBypassr.Useaccepts customMiddlewareFuncor you can usefunc(http.Handler) http.Handlerusingr.UseBypassNewRouter()acceptsOptions
type HandlerFunc func(w http.ResponseWriter, r *http.Request) errorExample:
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)