Skip to content

Instantly share code, notes, and snippets.

@JalfResi
Created February 2, 2017 21:40
Show Gist options
  • Select an option

  • Save JalfResi/87e8446b1bbf9506ce4143f89c7dfc9b to your computer and use it in GitHub Desktop.

Select an option

Save JalfResi/87e8446b1bbf9506ce4143f89c7dfc9b to your computer and use it in GitHub Desktop.
Golang HTTP Handler request/response logger
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)
}
}
@jacque006

Copy link
Copy Markdown

If you want to also keep the status code,

w.WriteHeader(rec.Code)

Note that I'm not 100% sure this is the correct way to do this.

@kei-yamazaki

kei-yamazaki commented Jun 12, 2018

Copy link
Copy Markdown

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