Created
April 28, 2017 12:07
-
-
Save lpalmes/0dca79dd9e2e6a094ff2f4afa297efdb to your computer and use it in GitHub Desktop.
Go middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the handler interface by the way, https://github.com/golang/go/blob/master/src/net/http/server.go#L81