Home  >  Article  >  Backend Development  >  How to Log Response Data from http.ResponseWriter in Go?

How to Log Response Data from http.ResponseWriter in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 01:41:02715browse

How to Log Response Data from http.ResponseWriter in Go?

Logging Data from http.ResponseWriter

In Go, you can use various techniques to log data emitted from an HTTP request-response cycle. One common question is obtaining the data written to the http.ResponseWriter for logging purposes.

Solution: Using io.MultiWriter

To capture the response data, you can utilize the io.MultiWriter to duplicate the writes to a separate writer. In your code, you can create a new bytes.Buffer instance as the log buffer and pass it as one of the writers to io.MultiWriter. By using the MultiWriter as the response writer, you can duplicate the response data into the log buffer.

Code Example:

<code class="go">import (
    "bytes"
    "io"
    "net/http"
)

func api1(w http.ResponseWriter, req *http.Request) {
    var log bytes.Buffer
    rsp := io.MultiWriter(w, &log)
    // Use rsp instead of w from this point onward
    // ...
}</code>

Now, the log buffer (log) will contain a copy of the response data written to the response writer.

Alternative Solution: Using io.TeeReader

To capture the request data, you can employ io.TeeReader. It creates a reader that writes whatever it reads from a given reader to a provided writer. In this case, you can use it to save a copy of the request body in the log buffer.

Code Example:

<code class="go">import (
    "bytes"
    "io"
    "net/http"
)

func api1(w http.ResponseWriter, req *http.Request) {
    var log bytes.Buffer
    tee := io.TeeReader(req.Body, &log)
    // Use tee instead of req.Body from this point onward
    // ...
}</code>

With io.TeeReader, the log buffer will include a copy of the request body content.

By utilizing these techniques, you can log both request and response data, facilitating comprehensive logging for API requests.

The above is the detailed content of How to Log Response Data from http.ResponseWriter 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