I'm trying to log the response body of a request that has been redirected.
func main() {
r := gin.Default()
eanAPI := api.NewEanAPI()
v1 := r.Group("/v1")
v1.POST("/*action", eanAPI.Redirect, middleware.SaveRequest())
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8000"
}
r.Run(":" + port)
}
func (api *eanAPI) Redirect(ctx *gin.Context) {
forwardToHost := "https://jsonplaceholder.typicode.com"
url := ctx.Request.URL.String()
ctx.Redirect(http.StatusTemporaryRedirect, forwardToHost)
}
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func SaveRequest() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = blw
c.Next()
statusCode := c.Writer.Status()
fmt.Println("status: ", statusCode)
if statusCode <= 400 {
//ok this is an request with error, let's make a record for it
// now print body (or log in your preferred way)
fmt.Println("Response body: " + blw.body.String())
}
}
Unfortunately, the body response is always empty. Maybe the redirection or the middleware is messing with my body response
When I tried with postman I can see the body response coming! You can try it by a POST on https://jsonplaceholder.typicode.com/posts. It should return a payload with an id in the body response
What am I doing wrong here?
Thanks in advance
</div>