Created
August 17, 2024 05:58
-
-
Save daniel-moya/b9c98d0ec96690ca141d9a81151c828f to your computer and use it in GitHub Desktop.
Chains middleware adapters into an http server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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