
🪄 muxify your mux setup in Go! muxify is a tiny go package that provides a minimal functionality mux that wraps around the go default http.ServeMux
. The muxify.Mux
simplifies and enhances the setup of the http.ServeMux
.
Wrap prefixes and middlewares without clutter. Spin up subrouters for clean organization of the request routing map.
More examples can be found in the wiki
go get github.com/42LM/muxify
muxify slightly adopts the syntax of gorilla/mux. It uses a common building block to create a router/subrouter for the serve mux builder.
It all starts with creating the muxify.ServeMuxBuilder
mux := muxify.NewMux()
Setup the router
mux.Handle("GET /", notFoundHandler)
Create a subrouter from the root router (prefix and middleware are optional)
subMux := mux.Subrouter()
subMux.Use(AdminMiddleware, ChorsMiddleware)
subMux.Prefix("/admin")
subMux.Handle("POST /{id}", createAdminHandler)
subMux.HandleFunc("DELETE /{id}", func(w http.ResponseWriter, r *http.Request) { w.Write("DELETE") })
Use it as usual
s.ListenAndServe(":8080", mux)
Tip
Check out the registered patterns
mux.PrintRegisteredPatterns()
Chaining is also possible
subMux := mux.Subrouter().Prefix("/v1").Use(Middleware1, Middleware2)
subMux.Handle("GET /topic/{id}", getTopicHandler)
First of all this project exists for the sake of actually using the golang http default serve mux <3.
The motivation for this project derives from the following two problems with the enhanced routing patterns for the http.ServeMux
:
1. Every single handler needs to be wrapped with middleware. This leads to alot of repeating code and moreover to very unreadable code, too. IMHO it already starts to get out of hands when one handler needs to be wrapped with more than four middlewares.
To give a little bit more context on this topic just take a look at the following code example:
mux.Handle("/foo", Middleware1(Middleware2(Middleware3(Middleware4(Middleware5(Middleware6(fooHandler)))))))So even for middlewares that maybe every handler should have (e.g. auth) this is pretty cumbersome to wrap every single handler in it.
💡 muxify provides a convenient way of wrapping patterns/routes with middleware and subrouters take over these middlewares.
It is not possible to use the
http.StripPrefix
without defining a pattern for the handler, but sometimes i want to just create a new subrouter from whatever router state.router.Handle("GET /ping", makePingHandler(endpoints, options)) subrouterV1 := http.NewServeMux() subrouterV1.Handle("/v1/", http.StripPrefix("/v1", router))Not being able to use a subrouter adds up to the other problem. A subrouter would help wrapping certain patterns/routes with middleware. A subrouter being created from another router/subrouter always inherits the middlewares.
💡 muxify enables the possibility of defining subrouters.