mirror of
https://github.com/ipfs/kubo.git
synced 2025-06-30 18:13:54 +08:00
Directly wire ctx into http request
License: MIT Signed-off-by: rht <rhtbot@gmail.com>
This commit is contained in:
@ -34,7 +34,7 @@ type Client interface {
|
||||
|
||||
type client struct {
|
||||
serverAddress string
|
||||
httpClient http.Client
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func NewClient(address string) Client {
|
||||
@ -43,7 +43,7 @@ func NewClient(address string) Client {
|
||||
// refused on 'client.Do'
|
||||
return &client{
|
||||
serverAddress: address,
|
||||
httpClient: http.Client{
|
||||
httpClient: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
DisableKeepAlives: true,
|
||||
},
|
||||
@ -103,7 +103,7 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
|
||||
|
||||
ec := make(chan error, 1)
|
||||
rc := make(chan cmds.Response, 1)
|
||||
dc := req.Context().Done()
|
||||
httpReq.Cancel = req.Context().Done()
|
||||
|
||||
go func() {
|
||||
httpRes, err := c.httpClient.Do(httpReq)
|
||||
@ -122,24 +122,17 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
|
||||
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
|
||||
select {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user