-
-
Save junxie6/957a30515a0eef79924fff8a374eafa1 to your computer and use it in GitHub Desktop.
Golang HTTP Handler request/response logger
This file contains hidden or 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment