Logging HTTP ResponseWriter Data
In Go, logging request and response data simultaneously can prove challenging. To address this, consider using io.MultiWriter, which duplicates all writes to multiple writers.
<code class="go">func api1(w http.ResponseWriter, req *http.Request) { var log bytes.Buffer rsp := io.MultiWriter(w, &log) // From this point onward, use rsp instead of w ... }</code>
With this setup, rsp duplicates writes to both w (the response writer) and the log buffer. The contents of the log buffer can then be captured for logging purposes.
Another option is to utilize io.TeeReader to duplicate reads from the request body. This ensures the request payload is logged as well.
<code class="go">func api1(w http.ResponseWriter, req *http.Request) { var log bytes.Buffer tee := io.TeeReader(req.Body, &log) err := json.NewDecoder(tee).Decode(&requestData) ... }</code>
In this scenario, json.Decoder reads from tee, effectively copying the request body into the log buffer.
By implementing these techniques, you can write meaningful logs that capture both request and response data, providing valuable information for troubleshooting and debugging purposes.
The above is the detailed content of How to Log Both Request and Response Data in Go?. For more information, please follow other related articles on the PHP Chinese website!