diff --git a/conn.go b/conn.go index 91a7e49..c5f5935 100644 --- a/conn.go +++ b/conn.go @@ -90,7 +90,9 @@ func (obj *connPool) taskMain(conn *connecotr, task *reqTask) (err error) { case <-conn.forceCtx.Done(): err = context.Cause(conn.forceCtx) case <-task.reqCtx.Context().Done(): - err = context.Cause(task.reqCtx.Context()) + if context.Cause(task.reqCtx.Context()) != errNoErr { + err = context.Cause(task.reqCtx.Context()) + } case <-task.bodyCtx.Done(): if context.Cause(task.bodyCtx) != errNoErr { err = context.Cause(task.bodyCtx) diff --git a/requests.go b/requests.go index 2b484e2..e411f39 100644 --- a/requests.go +++ b/requests.go @@ -142,7 +142,7 @@ func (obj *Client) retryRequest(ctx context.Context, option RequestOption, uhref if err != nil || loc == nil { return } - response.Close() + response.Close(nil) switch response.StatusCode() { case 307, 308: if response.Option().readOne { @@ -244,9 +244,10 @@ func (obj *Client) request(ctx *Response) (err error) { } //init ctx,cnl if ctx.option.Timeout > 0 { //超时 - ctx.ctx, ctx.cnl = context.WithTimeout(ctx.Context(), ctx.option.Timeout) + ctx.ctx, _ = context.WithTimeout(ctx.ctx, ctx.option.Timeout) + ctx.ctx, ctx.cnl = context.WithCancelCause(ctx.ctx) } else { - ctx.ctx, ctx.cnl = context.WithCancel(ctx.Context()) + ctx.ctx, ctx.cnl = context.WithCancelCause(ctx.Context()) } var isWebsocket bool //init Scheme diff --git a/response.go b/response.go index 84bd169..8d991b0 100644 --- a/response.go +++ b/response.go @@ -63,7 +63,7 @@ type Response struct { response *http.Response webSocket *websocket.Conn sse *SSE - cnl context.CancelFunc + cnl context.CancelCauseFunc option *RequestOption client *Client encoding string @@ -316,10 +316,10 @@ func (obj *Response) ReadBody() (err error) { return nil } defer func() { + obj.Close(err) if err != nil { obj.CloseConn() } else { - obj.Close() if obj.response.StatusCode == 101 && obj.webSocket == nil { obj.webSocket = websocket.NewConn(newFakeConn(obj.body.connStream()), func() { obj.CloseConn() }, true, obj.Headers().Get("Sec-WebSocket-Extensions")) } @@ -374,14 +374,22 @@ func (obj *Response) Proxys() []Address { // close func (obj *Response) CloseConn() { + obj.Close(errors.New("response close conn")) if obj.body != nil { obj.body.CloseConn() } } // close -func (obj *Response) Close() { +func (obj *Response) Close(err error) { if obj.body != nil { obj.body.Close() } + if obj.cnl != nil { + if err == nil { + obj.cnl(errNoErr) + } else { + obj.cnl(err) + } + } }