Chainer is a tiny Go package for assembling net/http middleware into a single
http.Handler. Links run in the order they are passed to NewChain, and each
link decides whether to continue to the next handler.
- Go 1.26
- Optional: mise for local toolchain management
Install the package:
go get github.com/maxwu/chainerCreate middleware links and assemble them into a handler:
package main
import (
"log"
"net/http"
"github.com/maxwu/chainer"
)
func logger(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)
})
}
func requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
http.Error(w, "missing authorization", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func hello(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("hello"))
}
func main() {
handler := chainer.NewChain(
chainer.LinkFunc(logger),
chainer.LinkFunc(requireAuth),
chainer.LinkFunc(func(_ http.Handler) http.Handler {
return http.HandlerFunc(hello)
}),
).GetHandler()
http.Handle("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}Use mise install to install the configured Go toolchain, then run:
make testThe test suite demonstrates gotest-labels for selecting tests by labels in test comment blocks.