I don't know if this question makes any sense, but I was wondering If there is any way to get the data which is written in http.ResponseWriter
. I need it for logging
.
I have written an api in Golang.
func api1(w http.ResponseWriter, req *http.Request) {
var requestData MyStruct
err := json.NewDecoder(req.Body).Decode(&requestData)
if err != nil {
writeError(w, "JSON request is not in correct format")
return
}
log.Println(" Request Data :", req.Body) // I am logging req
result, err := compute() // getting result from a function
if err != nil {
errRes := ErrorResponse{"ERROR", err}
response, er = json.Marshal(errRes) // getting error response
} else {
response, er = json.Marshal(result)
}
if er != nil {
http.Error(w, er.Error(), 500) // writing error
return
}
io.WriteString(w, string(response)) // writing response
}
The aim is to create a single log with request and response data
. The response can be either an error response or processed response.
I was thinking if I could get data which is written on http.ResponseWriter then, I can create single meaningful log.
Is this possible?
If not, please suggest how can I achieve this.