Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I recover the body of the response body by the middleware,this question has perplex me a few days,please help me,thank you all the same #2901

Open
jimmy-yu-1990 opened this issue Oct 16, 2021 · 1 comment

Comments

@jimmy-yu-1990
Copy link

Description

I want to write a middleware to intercept the response body and recover the response body ,I think that go use the responseWriter interface to io the response ,but it seems so hard to rewrite the body,

relation
https://stackoverflow.com/questions/33606330/golang-rewrite-http-request-body

@jimmy-yu-1990 jimmy-yu-1990 changed the title How do I recover the body of the response body by the middleware,this question has perplex me long days,please help me,thank you all the same How do I recover the body of the response body by the middleware,this question has perplex me a few days,please help me,thank you all the same Oct 16, 2021
@kszafran
Copy link
Contributor

I believe that the standard ResponseWriter writes directly to the HTTP response, so you couldn't extract the response body from it. You could however replace the Writer field in gin.Context with your own implementation of a ResponseWriter. For example some kind of wrapper around the default writer that would buffer the response, transform it, etc.

One way to go about it would be to create a struct like:

type MyResponseWriter {
    gin.ResponseWriter
}

// implement all the methods you need to override
func (w *MyResponseWriter) Write([]byte) (int, error) { ... }

And use it like:

c.Writer = &MyResponseWriter{c.Writer}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants