Search code examples
gogo-gin

How to log response body in gin while I redirect the initial request


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


Solution

  • The response body you're seeing in the browser/postman is from the page you're being redirected to. The page doing the actual redirecting likely has no response body, just a status and a Location header. This is the expected behavior of a redirect. If you want to try to capture the body of the page you're redirecting to, you can't actually use redirects for that (the redirect handler isn't involved in the final request); you'd have to fully proxy the request rather than redirecting it. Proxying is very different from redirecting though, so make sure that's really the behavior you're after.