The Mux package provides structures and methods for removing some of the boilerplate around setting up an HTTP server with routes, authentication middlewares, and static routes. It makes use of the standard Go library exclusively (requires Go 1.25.0 or higher) for routing, and the "autocert" library for Let's Encrypt.
Here is a short, basic example.
package main
import (
"context"
"net/http"
"github.com/adampresley/configinator"
"github.com/adampresley/httphelpers/responses"
"github.com/adampresley/mux"
)
type Config struct {
mux.Config
}
func main() {
config := Config{}
configinator.Behold(&config)
shutdownCtx, stopApp := context.WithCancel(context.Background())
routes := []mux.Route{
{Path: "/", HandlerFunc: helloHandler},
}
muxer := mux.Setup(
config,
routes,
shutdownCtx,
stopApp,
)
muxer.Start()
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
responses.TextOK(w, "Hello, World!")
}In this example, we need and setup the following:
- A cancellable context
- A config struct (that implements mux.MuxConfig
- Some routes with handlers
- Setup our mux
- Start the HTTP server (this blocks until the context is cancelled. terminate signals are built in)
A route is simply a structure that defines the handler and any middlewares for a given verb and path. Here is what that looks like:
mux.Route{
Path: "GET /about",
HandlerFunc: http.HandlerFunc(SomeHandlerFunc),
Middlewares: []mux.MiddlewareFunc{
SomeMiddlewareFunc,
}
}HandlerFunc (or Handler) and Path are the only fields required. Middlewares is optional.
Middleware functions allow you to run a method prior to a handler servicing the request. These functions can alter the request context, validate information, and more. Their signature looks like this.
func middlewareFunc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff
next.ServeHTTP(w, r)
})
}This library supports two ways to intercept requests with middlewares:
- Router-level
- Per route
- Built-in authentication middlewares via configuration
Router-level middlewares are applied to all routes. This is useful in situations such as logging. Here is a simple example:
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("request path: %s\n", r.Path)
})
}
muxer := mux.Setup(
&config,
routes,
shutdownCtx,
stopApp,
mux.WithMiddlewares(loggingMiddleware),
)Per-route middlewares are middlewares that are only applied to a single route. This is useful if you wish to intercept a single request to perform some action.
func testMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do something here.
})
}
routes := []mux.Route{
{Path: "GET /about", HandlerFunc: aboutHandler, Middlewares: []mux.MiddlewareFunc{testMiddleware}},
}To serve static assets you will need to do four things:
- Create a folder where static assets live. For example:
/app - Create a sub-folder that matches what your static asset path should be:
/app/static - Add an embed to your application
- Add static content configuration to the router
All of your static assets should live inside the sub-folder static. Here is
a sample of the code for setting up static assets.
import (
"embed"
)
var (
//go:embed app
appFS embed.FS
)
muxer := mux.Setup(
&config,
routes,
shutdownCtx,
stopApp,
mux.WithStaticContent("app", "/static/", appFS),
mux.WithStaticCacheControl("public, max-age=31536000"),
mux.WithGzipForStaticFiles(),
)