Home >Backend Development >Golang >How to Log Both Request and Response Data in Go?

How to Log Both Request and Response Data in Go?

DDD
DDDOriginal
2024-11-06 14:37:02770browse

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>

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!

Statement:
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