Skip to content

Instantly share code, notes, and snippets.

@vyskocilm
Created December 18, 2018 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyskocilm/9f6ea49623470e4c98052ed62f4e6845 to your computer and use it in GitHub Desktop.
Save vyskocilm/9f6ea49623470e4c98052ed62f4e6845 to your computer and use it in GitHub Desktop.
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