duan205571 2018-09-14 13:32
浏览 275
已采纳

当我重定向初始请求时,如何在gin中记录响应正文

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>
  • 写回答

1条回答 默认 最新

  • dongzhuo6137 2018-09-14 13:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip