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

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

Patricia Arquette
Release: 2024-11-06 01:41:02
Original
793 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template