|
| 1 | +package decorator |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net/http" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +type HttpHandlerDecorator func(http.HandlerFunc) http.HandlerFunc |
| 10 | + |
| 11 | +func Handler(h http.HandlerFunc, decors ...HttpHandlerDecorator) http.HandlerFunc { |
| 12 | + for i := range decors { |
| 13 | + d := decors[len(decors)-1-i] // iterate in reverse |
| 14 | + h = d(h) |
| 15 | + } |
| 16 | + return h |
| 17 | +} |
| 18 | + |
| 19 | +func WithServerHeader(h http.HandlerFunc) http.HandlerFunc { |
| 20 | + return func(w http.ResponseWriter, r *http.Request) { |
| 21 | + log.Println("--->WithServerHeader()") |
| 22 | + w.Header().Set("Server", "HelloServer v0.0.1") |
| 23 | + h(w, r) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func WithAuthCookie(h http.HandlerFunc) http.HandlerFunc { |
| 28 | + return func(w http.ResponseWriter, r *http.Request) { |
| 29 | + log.Println("--->WithAuthCookie()") |
| 30 | + cookie := &http.Cookie{Name: "Auth", Value: "Pass", Path: "/"} |
| 31 | + http.SetCookie(w, cookie) |
| 32 | + h(w, r) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +func WithBasicAuth(h http.HandlerFunc) http.HandlerFunc { |
| 37 | + return func(w http.ResponseWriter, r *http.Request) { |
| 38 | + log.Println("--->WithBasicAuth()") |
| 39 | + cookie, err := r.Cookie("Auth") |
| 40 | + if err != nil || cookie.Value != "Pass" { |
| 41 | + w.WriteHeader(http.StatusForbidden) |
| 42 | + return |
| 43 | + } |
| 44 | + h(w, r) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func WithDebugLog(h http.HandlerFunc) http.HandlerFunc { |
| 49 | + return func(w http.ResponseWriter, r *http.Request) { |
| 50 | + log.Println("--->WithDebugLog") |
| 51 | + r.ParseForm() |
| 52 | + log.Println(r.Form) |
| 53 | + log.Println("path", r.URL.Path) |
| 54 | + log.Println("scheme", r.URL.Scheme) |
| 55 | + log.Println(r.Form["url_long"]) |
| 56 | + for k, v := range r.Form { |
| 57 | + log.Println("key:", k) |
| 58 | + log.Println("val:", strings.Join(v, "")) |
| 59 | + } |
| 60 | + h(w, r) |
| 61 | + } |
| 62 | +} |
0 commit comments