Skip to content

Instantly share code, notes, and snippets.

@daniel-moya
Created August 17, 2024 05:58
Show Gist options
  • Save daniel-moya/b9c98d0ec96690ca141d9a81151c828f to your computer and use it in GitHub Desktop.
Save daniel-moya/b9c98d0ec96690ca141d9a81151c828f to your computer and use it in GitHub Desktop.
Chains middleware adapters into an http server
type Adapter func(http.Handler) http.Handler
func Metric() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Metric")
h.ServeHTTP(w, r)
})
}
}
func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
for _, adapter := range adapters {
h = adapter(h)
}
return h
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", handleHello)
http.ListenAndServe(":8080", Adapt(mux, Metric()))
}
func handleHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Basic API"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment