Created
August 5, 2015 13:55
-
-
Save eahydra/75f8af2bdfa7203ac781 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 ( | |
"log" | |
"net/http" | |
"os" | |
) | |
type HandlerWrapper func(http.ResponseWriter, *http.Request) | |
func (h HandlerWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
h(w, r) | |
} | |
type Decorator func(http.Handler) http.Handler | |
func Logging(l *log.Logger) Decorator { | |
return func(h http.Handler) http.Handler { | |
return HandlerWrapper(func(w http.ResponseWriter, r *http.Request) { | |
l.Println(r.URL.String(), r.RemoteAddr) | |
h.ServeHTTP(w, r) | |
}) | |
} | |
} | |
func Header(key, name string) Decorator { | |
return func(h http.Handler) http.Handler { | |
return HandlerWrapper(func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Add(key, name) | |
h.ServeHTTP(w, r) | |
}) | |
} | |
} | |
func BuildDecorator(h http.Handler, decrorator ...Decorator) http.Handler { | |
for _, de := range decrorator { | |
h = de(h) | |
} | |
return h | |
} | |
func HandleQuery(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Hello Decorator")) | |
} | |
func main() { | |
logger := log.New(os.Stdout, "Test", log.Ldate) | |
http.Handle("/query", BuildDecorator( | |
HandlerWrapper(HandleQuery), | |
Logging(logger), | |
Header("TTT", "VVV"))) | |
http.ListenAndServe(":9990", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment