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 38
| type HttpHandlerDecorator func(http.HandlerFunc) http.HandlerFunc
func Handler(h http.HandlerFunc, decors ...HttpHandlerDecorator) http.HandlerFunc { for i := range decors { h = decors[len(decors)-1-i](h) } return h }
func WithServerHeader(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { log.Println("--->WithServerHeader") w.Header().Set("Server", "HelloServer v0.0.1") h(w, r) } }
func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { log.Println("--->WithAuthCookie") cookie := http.Cookie{Name: "Auth", Value: "SimpleAuth"} http.SetCookie(w, &cookie) h(w, r) } }
func hello(w http.ResponseWriter, r *http.Request) { log.Printf("Recieved Request %s from %s\n", r.URL.Path, r.RemoteAddr) _, _ = fmt.Fprintf(w, "Hello, World! "+r.URL.Path) }
func main() { http.Handle("/v1/hello", Handler(hello, WithServerHeader, WithAuthCookie)) err := http.ListenAndServe(":8000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
|