This package is a fast HTTP multiplexer.
It uses a radix tree to match URLs. When matching simple routes, it's a zero allocation search. It's fast, simple and supports middlewares in an elegant way.
Full documentation [here].
vgo get -u github.com/gbrlsnchs/mux
go get -u github.com/gbrlsnchs/mux
import (
// ...
"github.com/gbrlsnchs/mux"
)
type key uint8
const ctxKey key = 0
rt := mux.NewRouter("/api", ctxKey)
rt.HandleFunc(http.MethodGet, "/ping", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
})
func loggingFunc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
rt := mux.NewRouter("/api")
rt.Use(loggingFunc)
rt.Handle(http.MethodGet, "/ping", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
}))
func handler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
func authFunc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if mux.Params(r.Context(), ctxKey)["secret"] != "my_secret" {
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func permissionFunc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !userIsAdmin(r) { // hypothetical function
w.WriteHeader(http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
rt := mux.NewRouter("/", ctxKey)
guard := mux.NewChain(authFunc, permissionFunc)
rt.Handle(http.MethodPost, "/unprotected", handler)
rt.Handle(http.MethodPost, "/protected/:secret", guard(handler))
- For bugs and opinions, please open an issue
- For pushing changes, please open a pull request