提交 45999946 作者: rht

Directly wire ctx into http request

License: MIT
Signed-off-by: 's avatarrht <rhtbot@gmail.com>
上级 f631db7e
...@@ -34,7 +34,7 @@ type Client interface { ...@@ -34,7 +34,7 @@ type Client interface {
type client struct { type client struct {
serverAddress string serverAddress string
httpClient http.Client httpClient *http.Client
} }
func NewClient(address string) Client { func NewClient(address string) Client {
...@@ -43,7 +43,7 @@ func NewClient(address string) Client { ...@@ -43,7 +43,7 @@ func NewClient(address string) Client {
// refused on 'client.Do' // refused on 'client.Do'
return &client{ return &client{
serverAddress: address, serverAddress: address,
httpClient: http.Client{ httpClient: &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
DisableKeepAlives: true, DisableKeepAlives: true,
}, },
...@@ -103,7 +103,7 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { ...@@ -103,7 +103,7 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
ec := make(chan error, 1) ec := make(chan error, 1)
rc := make(chan cmds.Response, 1) rc := make(chan cmds.Response, 1)
dc := req.Context().Done() httpReq.Cancel = req.Context().Done()
go func() { go func() {
httpRes, err := c.httpClient.Do(httpReq) httpRes, err := c.httpClient.Do(httpReq)
...@@ -122,24 +122,17 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { ...@@ -122,24 +122,17 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
rc <- res rc <- res
}() }()
for { select {
select { case err := <-ec:
case <-dc: return nil, err
log.Debug("Context cancelled, cancelling HTTP request...") case res := <-rc:
tr := http.DefaultTransport.(*http.Transport) if found && len(previousUserProvidedEncoding) > 0 {
tr.CancelRequest(httpReq) // reset to user provided encoding after sending request
dc = nil // Wait for ec or rc // NB: if user has provided an encoding but it is the empty string,
case err := <-ec: // still leave it as JSON.
return nil, err req.SetOption(cmds.EncShort, previousUserProvidedEncoding)
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
} }
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论