Skip to content

Instantly share code, notes, and snippets.

@eahydra
Created August 5, 2015 13:55
Show Gist options
  • Save eahydra/75f8af2bdfa7203ac781 to your computer and use it in GitHub Desktop.
Save eahydra/75f8af2bdfa7203ac781 to your computer and use it in GitHub Desktop.
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