Created
December 18, 2018 13:11
-
-
Save vyskocilm/9f6ea49623470e4c98052ed62f4e6845 to your computer and use it in GitHub Desktop.
Stacked http.Handler in golang
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
// | |
// 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