Commit f46443c2 authored by Tor Arne Vestbø's avatar Tor Arne Vestbø Committed by Tor Arne Vestbø

Teach http client to cancel request on context cancellation

The context may be cancelled while a request is in flight. We need to
handle this and cancel the request. The code is based on the ideas
from https://blog.golang.org/context
parent 47b61ce3
...@@ -82,25 +82,44 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { ...@@ -82,25 +82,44 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
version := config.CurrentVersionNumber version := config.CurrentVersionNumber
httpReq.Header.Set("User-Agent", fmt.Sprintf("/go-ipfs/%s/", version)) httpReq.Header.Set("User-Agent", fmt.Sprintf("/go-ipfs/%s/", version))
httpRes, err := http.DefaultClient.Do(httpReq) ec := make(chan error, 1)
if err != nil { rc := make(chan cmds.Response, 1)
return nil, err dc := req.Context().Context.Done()
}
// using the overridden JSON encoding in request
res, err := getResponse(httpRes, req)
if err != nil {
return nil, err
}
if found && len(previousUserProvidedEncoding) > 0 { go func() {
// reset to user provided encoding after sending request httpRes, err := http.DefaultClient.Do(httpReq)
// NB: if user has provided an encoding but it is the empty string, if err != nil {
// still leave it as JSON. ec <- err
req.SetOption(cmds.EncShort, previousUserProvidedEncoding) return
}
// using the overridden JSON encoding in request
res, err := getResponse(httpRes, req)
if err != nil {
ec <- err
return
}
rc <- res
}()
for {
select {
case <-dc:
log.Debug("Context cancelled, cancelling HTTP request...")
tr := http.DefaultTransport.(*http.Transport)
tr.CancelRequest(httpReq)
dc = nil // Wait for ec or rc
case err := <-ec:
return nil, err
case res := <-rc:
if found && len(previousUserProvidedEncoding) > 0 {
// reset to user provided encoding after sending request
// NB: if user has provided an encoding but it is the empty string,
// still leave it as JSON.
req.SetOption(cmds.EncShort, previousUserProvidedEncoding)
}
return res, nil
}
} }
return res, nil
} }
func getQuery(req cmds.Request) (string, error) { func getQuery(req cmds.Request) (string, error) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment