Skip to content

Instantly share code, notes, and snippets.

@lpalmes
Created April 28, 2017 12:07
Show Gist options
  • Save lpalmes/0dca79dd9e2e6a094ff2f4afa297efdb to your computer and use it in GitHub Desktop.
Save lpalmes/0dca79dd9e2e6a094ff2f4afa297efdb to your computer and use it in GitHub Desktop.
Go middleware
package main
import (
"log"
"net/http"
"time"
)
func main() {
http.Handle("/", logging(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
})))
log.Fatal(http.ListenAndServe(":3000", nil))
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
log.Printf("%s %s <-", r.Method, r.URL.String())
next.ServeHTTP(w, r)
log.Printf("%s %s ->", r.Method, r.URL.String())
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
})
}
@lpalmes
Copy link
Author

lpalmes commented Apr 28, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment