Skip to content

danikarik/mux

Repository files navigation

danikarik/mux

Is a small wrapper around gorilla/mux with few additions:

  • r.HandleFunc accepts custom HandlerFunc or you can use http.HandlerFunc using r.HandleFuncBypass
  • r.Use accepts custom MiddlewareFunc or you can use func(http.Handler) http.Handler using r.UseBypass
  • NewRouter() accepts Options

HandlerFunc

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)

MiddlewareFunc

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)

Options

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)

About

A small wrapper around 🦍 mux.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages