Answer the question
In order to leave comments, you need to log in
How to make a server middleware in gorilla mux?
I need to catch the server's response , get the response body from it and log it, let's say to the console.
Can you tell me how to get access to the response body in middleware?
Answer the question
In order to leave comments, you need to log in
There is an option to use httptest.ResponseRecorder, I used it earlier to write tests.
https://pkg.go.dev/net/http/httptest#ResponseRecorder
An example would be something like this
func (m *LoggingMiddleware) LogBody(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
wRecorder := httptest.NewRecorder()
next.ServeHTTP(wRecorder, r)
resp := wRecorder.Result()
body, _ := io.ReadAll(resp.Body)
// не забыть записать ответ в w
}
return http.HandlerFunc(fn)
}
func (m *LoggingMiddleware) LogBody(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
logWriter := NewLogToConsoleResponseWriter(&b)
next.ServeHTTP(logWriter, r)
// тут у вас в buf будет ответ сервера, с которым можно работать
// главное потом не забыть записать его в `w`
}
return http.HandlerFunc(fn)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question