Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stacked http.Handler in golang
//
// Stacking net/http handlers
// vyskocilm.github.io/blog
//
package main
import (
"fmt"
"log"
"net/http"
)
// "middleware", some code run BEFORE business handlers
// note that it CONSUME http.Handler and return http.Handler
func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Middleware: ...")
w.Header().Set("x-middleware", "Middleware")
h.ServeHTTP(w, r)
log.Printf("... Middleware")
})
}
func main() {
mux := http.NewServeMux()
// register business logic handler
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("mux.HandleFunc(\"/\")")
fmt.Fprintf(w, "<html>Hello world</html>\n")
})
// wrap the middleware
handler := Middleware(mux)
// call the handler
log.Fatal(http.ListenAndServe(":8000", handler))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment