go http middleware
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package main
import ( "fmt" "net/http" "strings" )
func buildHandlerChain(apiHandler http.Handler) http.Handler { handler := WithAuthorization(apiHandler) handler = WithAuthentication(handler) return handler } func WithAuthentication(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { fmt.Printf("----handle Authentication-------\n") handler.ServeHTTP(w, req) }) }
func WithAuthorization(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { fmt.Printf("----handle Authorization-------\n") handler.ServeHTTP(w, req) }) }
func baseHandler(w http.ResponseWriter, req *http.Request) { fmt.Println("----base handler----\n") w.Write([]byte("hello handler!")) }
func main() { apiHandler := http.HandlerFunc(baseHandler) http.Handle("/", buildHandlerChain(apiHandler)) http.ListenAndServe(":3000", nil) }
|
1 2 3 4 5 6 7 8
| ---- ------- ---- ------- ---- ----
---- ------- ---- ------- ---- ----
|
Reference