-
-
Save didi1246888/a99264b00ceac119171b1d594e2c6e8a to your computer and use it in GitHub Desktop.
This file contains 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
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
func authMiddleware(f http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
if token := r.Header.Get("token"); token != "fake_token" { | |
_, _ = w.Write([]byte("unauthorized\n")) | |
return | |
} | |
f(w, r) | |
} | |
} | |
func loggerMiddleware(f http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("before") | |
f(w, r) | |
fmt.Println("after") | |
} | |
} | |
type handler func(http.HandlerFunc) http.HandlerFunc | |
// Aggregate handler and middleware | |
func pipelineHandlers(h http.HandlerFunc, hs ...handler) http.HandlerFunc { | |
for i := range hs { | |
h = hs[i](h) | |
} | |
return h | |
} | |
func handleHello(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("handle hello") | |
_, _ = w.Write([]byte("Hello World!\n")) | |
} | |
func main() { | |
http.HandleFunc("/hello", pipelineHandlers(handleHello, loggerMiddleware, authMiddleware)) | |
fmt.Println(http.ListenAndServe(":8888", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment