提交 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,13 +122,7 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { ...@@ -122,13 +122,7 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
rc <- res rc <- res
}() }()
for {
select { 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: case err := <-ec:
return nil, err return nil, err
case res := <-rc: case res := <-rc:
...@@ -140,7 +134,6 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { ...@@ -140,7 +134,6 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
} }
return res, nil return res, nil
} }
}
} }
func getQuery(req cmds.Request) (string, error) { func getQuery(req cmds.Request) (string, error) {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论