1

When I use the GoLand tool for debugging,After using HttpClient to request an address in Middleware, the status of the original r *http.Request.Body becomes closed, resulting in an exception during parsing in the Handler: error: http: invalid Read on closed Body.

Middleware:

func (m *AuthorizeHandlerMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        if token == "" {
            res := types.Base{
                Code:    401,
                Message: "error",
            }
            logc.Error(r.Context(), "token is empty")
            httpx.OkJsonCtx(r.Context(), w, res)
            return
        }
        hReq, err := http.NewRequest("GET", "http://localhost:801/admin/member/info", nil)
        if err != nil {
            logc.Error(r.Context(), err)
            return
        }
        c := http.Client{}
        _, _ = c.Do(hReq)  //After executing this step, r.Body's Close becomes True.
        next(w, r)
    }
}

Handler

func MyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        var req types.MyReq
        if err := httpx.Parse(r, &req); err != nil {
            // error : http: invalid Read on closed Body.
            httpx.ErrorCtx(r.Context(), w, err)  
            return
        }

        l := logic.NewAnaliysisPnrLogic(r.Context(), svcCtx)
        resp, err := l.AnaliysisPnr(&req)
        if err != nil {
            httpx.ErrorCtx(r.Context(), w, err)
        } else {
            httpx.OkJsonCtx(r.Context(), w, resp)
        }
    }
}

Please help me check the reason for the problem. Thank you.

nil
  • 59
  • 4
  • `c.Do(hReq)` makes no reference to `r`, so there is no way to could cause it to close. There must be someting else you are not showing here. – JimB Aug 08 '23 at 15:03
  • I'm using the go-zero framework, and these codes are auto-generated. I've also been unable to figure out where it's affecting 'r'. – nil Aug 08 '23 at 15:08
  • Did you search for this error at all to understand what it means? Something in your code is responding to the client before getting to `httpx.Parse(r, &req)` which causes the connection to close (unless of course something is closing it explicitly). Are there any other handlers running before or after the `AuthorizeHandlerMiddleware`? I also doubt that `_, _ = c.Do(hReq)` is automatically generated with the intent of being used as shown, because it fails to read and close the body and leaks the connection. – JimB Aug 08 '23 at 15:25
  • @JimB Thank you for your response. After I used ```http.NewRequestWithContext(r.Context()...```, the issue no longer occurred. – nil Aug 09 '23 at 03:24

1 Answers1

1

The reason is that the HTTP server's Timeout in Go-zero defaults to 3 seconds, causing a timeout in Debug mode.

nil
  • 59
  • 4