Created
February 2, 2017 21:40
-
-
Save JalfResi/87e8446b1bbf9506ce4143f89c7dfc9b to your computer and use it in GitHub Desktop.
Golang HTTP Handler request/response logger
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
func logger(prefix string, h http.Handler) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
// Save a copy of this request for debugging. | |
requestDump, err := httputil.DumpRequest(r, false) | |
if err != nil { | |
log.Println(err) | |
} | |
log.Println(prefix, string(requestDump)) | |
rec := httptest.NewRecorder() | |
h.ServeHTTP(rec, r) | |
dump, err := httputil.DumpResponse(rec.Result(), false) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(prefix, string(dump)) | |
// we copy the captured response headers to our new response | |
for k, v := range rec.Header() { | |
w.Header()[k] = v | |
} | |
// grab the captured response body | |
data := rec.Body.Bytes() | |
w.Write(data) | |
} | |
} |
w.WriteHeader(rec.Code)
needs to be called before w.Write(data)
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to also keep the status code,
Note that I'm not 100% sure this is the correct way to do this.