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 39 40 41
| type Adapter func(http.Handler) http.Handler
func Logging(logger *log.Logger) Adapter { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request{ logger.Println(r.Method, r.URL.Path) h.ServeHTTP(w, r) }) } }
func WithHeader(key, value string) Adapter{ return func(h http.Handler) http.Handler{ return http.HanderFunc(func(w http.ResponseWriter, r *http.Request){ w.Header.Add(key, value) h.ServeHTTP(w, r) } } }
func Adapt(h http.Handler, adapters ...Adapter) http.Handler{ for _, adapter := range adapters{ h = adapter(h) } return h }
func main(){ router := mux.NewRouter() router.Handle("/", Adapt(someHandler, WithHeader("X-something", "Specific")))
http.Handle("/", Adapt(router, WithHeader("Server", "MyApp") Logging(logger) )) }
|