如何从中间件记录响应主体?

I tried to log the response body from middleware. I can get all the data related to the Request object. Now try to log the response code and response body for a single request.

I was trying to catch the response body and response code from w http.ResponseWriter, but could not succeed. Here is the sample code. I am using go's default http and logrus for logging.

next.ServeHTTP(w, r.WithContext(ctx))
end := time.Now().UTC()
latency := end.Sub(start)
// request logging
log.WithFields(log.Fields{
    "path":      r.URL.Path,
    "method":    r.Method,
    "body":      body,
    "auth_user": claims,
    "latency":   latency,
    "useragent": r.Header.Get("User-Agent"),
    "response_body": ,// cannot get response body here
    "status": "", //cannot get response header here
}).Info("request data")

Can someone help me with that, please?

To get response body and status code, you have to implement your own ResponseWriter. Here you can find full example