I
I
impressive172021-11-20 16:11:35
go
impressive17, 2021-11-20 16:11:35

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

1 answer(s)
E
Evgeny Mamonov, 2021-11-20
@impressive17

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)
}

An example of its use from the official documentation https://pkg.go.dev/net/http/httptest#example-Respo...
Or, you can make your own responseWriter, pass your writer to the handler, and then, after processing, write the received response server into original responseWriter
Something like this
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 question

Ask a Question

731 491 924 answers to any question