How to Log Both Request and Response Data in Go?

DDD
Release: 2024-11-06 14:37:02
Original
604 people have browsed it

How to Log Both Request and Response Data in Go?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!