我正在使用http.Client长轮询的客户端实现:
resp, err := client.Post(url, "application/json", bytes.NewBuffer(jsonPostBytes))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var results []*ResponseMessage
err = json.NewDecoder(resp.Body).Decode(&results) // code blocks here on long-poll
Run Code Online (Sandbox Code Playgroud)
是否有标准方法来抢占/取消客户端的请求?
我想调用resp.Body.Close()会这样做,但是我必须从另一个goroutine那里调用它,因为客户端通常已经被阻止阅读长轮询的响应.
我知道有一种方法可以设置超时http.Transport,但我的应用程序逻辑需要根据用户操作进行取消,而不仅仅是超时.
the*_*hai 17
标准方法是使用类型的上下文context.Context并将其传递给取消请求时需要知道的所有函数.
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
tr := &http.Transport{}
client := &http.Client{Transport: tr}
c := make(chan error, 1)
go func() { c <- f(client.Do(req)) }()
select {
case <-ctx.Done():
tr.CancelRequest(req)
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}
Run Code Online (Sandbox Code Playgroud)
golang.org/x/net/context
// A Context carries a deadline, cancelation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
Run Code Online (Sandbox Code Playgroud)
来源和更多信息,请访问https://blog.golang.org/context
更新
正如Paulo所提到的,Request.Cancel现已弃用,作者应将上下文传递给请求本身(使用*Request.WithContext)并使用上下文的取消通道(取消请求).
package main
import (
"context"
"net/http"
"time"
)
func main() {
cx, cancel := context.WithCancel(context.Background())
req, _ := http.NewRequest("GET", "http://google.com", nil)
req = req.WithContext(cx)
ch := make(chan error)
go func() {
_, err := http.DefaultClient.Do(req)
select {
case <-cx.Done():
// Already timedout
default:
ch <- err
}
}()
// Simulating user cancel request
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
}()
select {
case err := <-ch:
if err != nil {
// HTTP error
panic(err)
}
print("no error")
case <-cx.Done():
panic(cx.Err())
}
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*tto 13
现在不推荐使用CancelRequest.
当前策略是使用http.Request.WithContext传递具有截止时间的上下文,否则将被取消.之后就像正常的请求一样使用它.
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
req = req.WithContext(ctx)
resp, err := client.Do(req)
// ...
Run Code Online (Sandbox Code Playgroud)
不,client.Post是一个方便的包装器,用于90%的用例,不需要请求取消.
可能只需重新实现您的客户端就可以访问具有CancelRequest()函数的底层Transport对象.
只是一个简单的例子:
package main
import (
"log"
"net/http"
"time"
)
func main() {
req, _ := http.NewRequest("GET", "http://google.com", nil)
tr := &http.Transport{} // TODO: copy defaults from http.DefaultTransport
client := &http.Client{Transport: tr}
c := make(chan error, 1)
go func() {
resp, err := client.Do(req)
// handle response ...
_ = resp
c <- err
}()
// Simulating user cancel request channel
user := make(chan struct{}, 0)
go func() {
time.Sleep(100 * time.Millisecond)
user <- struct{}{}
}()
for {
select {
case <-user:
log.Println("Cancelling request")
tr.CancelRequest(req)
case err := <-c:
log.Println("Client finished:", err)
return
}
}
}
Run Code Online (Sandbox Code Playgroud)