Skip to content

Repository files navigation

Chainer

codecov Go Report Card

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.

Requirements

  • Go 1.26
  • Optional: mise for local toolchain management

Usage

Install the package:

go get github.com/maxwu/chainer

Create 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))
}

Development

Use mise install to install the configured Go toolchain, then run:

make test

References

The test suite demonstrates gotest-labels for selecting tests by labels in test comment blocks.

About

Chain HTTP middleware functions to a http.Handler

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages