Skip to content

Instantly share code, notes, and snippets.

@sheenobu
Created September 19, 2016 19:53
Show Gist options
  • Save sheenobu/49af43347a07eb8519f8dc9d6070f396 to your computer and use it in GitHub Desktop.
Save sheenobu/49af43347a07eb8519f8dc9d6070f396 to your computer and use it in GitHub Desktop.
http middleware log
package main
import (
"log"
"net/http"
"os"
)
type Adapter func(http.Handler) http.Handler
func Notify(logger *log.Logger) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Println("before")
h.ServeHTTP(w, r)
logger.Println("after")
})
}
}
func main() {
l := log.New(os.Stdout, "HTTP | ", log.LstdFlags|log.Lshortfile)
l2 := log.New(os.Stderr, "", log.LstdFlags)
f := func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("hello"))
l2.Println("during")
}
http.Handle("/", Notify(l)(http.HandlerFunc(f)))
http.ListenAndServe(":8888", nil)
}
HTTP | 2016/09/19 15:51:55 test.go:15: before
2016/09/19 15:51:55 during
HTTP | 2016/09/19 15:51:55 test.go:17: after
HTTP | 2016/09/19 15:51:55 test.go:15: before
2016/09/19 15:51:55 during
HTTP | 2016/09/19 15:51:55 test.go:17: after
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment