当我重定向初始请求时如何在杜松子酒中记录响应 body

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

我正在尝试记录已重定向请求的响应 body。

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

不幸的是,body 响应始终为空。也许是重定向或中间件干扰了我的 body 响应

当我尝试使用邮递员时,我可以看到 body 响应即将到来!您可以在 https://jsonplaceholder.typicode.com/posts 上通过 POST 尝试。它应该 return 在 body 响应

中带有 id 的有效负载

我做错了什么?

提前致谢

您在 browser/postman 中看到的响应 body 来自您被重定向到 的页面。执行实际重定向的页面可能没有响应 body,只有状态和 Location header。这是重定向的预期行为。如果您想尝试捕获要重定向到的页面的 body,您实际上不能为此使用重定向(重定向处理程序不涉及最终请求);您必须完全代理请求而不是重定向它。代理与重定向有很大不同,因此请确保这确实是您所追求的行为。