Skip to content

Instantly share code, notes, and snippets.

@foolishway
Created April 20, 2020 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foolishway/4e88385cfb60083e2782ea6aeaadf336 to your computer and use it in GitHub Desktop.
Save foolishway/4e88385cfb60083e2782ea6aeaadf336 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
"os"
)
type Adapter func(http.Handler) http.Handler
func main() {
indexHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("indexHandler say hello."))
})
indexHandler = Adapte(indexHandler, logHandler(log.New(os.Stdout, "handler:", 0)),
logHandler(log.New(os.Stdout, "log:", 0))).(http.HandlerFunc)
http.ListenAndServe(":8003", indexHandler)
}
func Adapte(handler http.Handler, ads ...Adapter) http.Handler {
for _, ad := range ads {
handler = ad(handler)
}
return handler
}
func logHandler(logger *log.Logger) Adapter {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Printf("log someting.")
handler.ServeHTTP(w, r)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment