如何提前关闭/中止 Golang http.Client 的 POST 请求

11
我正在使用 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

在客户端,有没有一种标准的方法来预先中止/取消请求?

我认为调用resp.Body.Close()可以实现这一功能,但我必须从另一个goroutine中调用它,因为客户端通常已经被阻塞在读取长轮询响应时。

我知道可以通过http.Transport设置超时,但我的应用程序逻辑需要根据用户操作来取消请求,而不仅仅是超时。

5个回答

27

使用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)
// ...

19

标准做法是使用类型为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
    }
}

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{}
}

源代码和更多信息请参见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())
    }

}

1
你甚至不需要额外的 goroutine 或特殊的客户端。只需设置 req.Cancel = ctx.Done(),它就会为您处理一切。 - captncraig
自从我发布答案以来,http库已经进行了多次更新。现在提供的最惯用的解决方案是由@Paulo提供的。 - themihai
@captncraig,我已经更新了我的答案。如果方法再次更改(虽然我怀疑不会),请随时编写新的答案,并希望它能得到应有的投票。我认为SO的作者不负责维护。投票系统应该在这方面提供帮助。 - themihai
这是关于您代码中更新部分的问题。我对Go不熟悉,但这看起来是错误的。想法是取消请求,在这里第一个Go例程会一直运行,直到请求实际完成。您没有取消它,只是根据谁先完成在主线程中继续前进。 - shadow
@shadow,我已经更新了答案,包括实际取消操作(WithCancel)。 - themihai

7

不需要请求取消的情况下,client.Post是一个方便的包装器,可以满足90%的使用场景。

可能只需重新实现客户端以访问底层的Transport对象,该对象具有CancelRequest()函数即可。

这里是一个快速示例:

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
        }
    }
}

2
并不是这个答案所关注的,但通常最好使用http.DefaultTransport,它具有合理的超时设置(和ProxyFromEnvironment),而不是一个空的Transport。 - JimB
3
当然,不要完全按照上面的例子写代码。这只是一个简化的示例,并且它在调用client.Do返回的*http.Response之后没有调用resp.Body.Close(),这是不合适的。绝不要这样做。 - Dave C
啊,tr.CancelRequest()(以及相关的示例代码)就是我在寻找的。 - George Armhold
@CaffeineComa,如果您可以取消接受此答案并接受下面Paulo或Themihai的答案,那就太好了。现在有更好的答案。 - captncraig

2
自Go 1.13版本以来,又新增了一个函数NewRequestWithContext,它接受一个Context参数用于控制整个出站Request的生命周期,并可与Client.DoTransport.RoundTrip一起使用。
这个函数可以代替先调用NewRequest再调用Request.WithContext的方式。详情请见:https://golang.org/doc/go1.13#net/http
req, err := http.NewRequest(...)
if err != nil {...}
req.WithContext(ctx)

变成

req, err := http.NewRequestWithContext(ctx, ...)
if err != nil {...}

1

@Paulo Casaretto的回答是正确的,应该使用http.Request.WithContext

这里有一个完整的演示(注意时间数字:5、10、30秒)。

HTTP服务器:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("before sleep")
    time.Sleep(10 * time.Second)
    fmt.Println("after sleep")

    fmt.Fprintf(w, "Hi")
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":9191", nil))
}

HTTP服务器控制台输出:

before sleep
after sleep 

HTTP客户端:

package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    go func() {
        fmt.Println("before request")
        client := &http.Client{Timeout: 30 * time.Second}
        req, err := http.NewRequest("GET", "http://127.0.0.1:9191", nil)
        if err != nil {
            panic(err)
        }
        req = req.WithContext(ctx)
        _, err = client.Do(req)
        if err != nil {
            panic(err)
        }
        fmt.Println("will not reach here")
    }()

    time.Sleep(5 * time.Second)
    cancel()
    fmt.Println("finished")
}

HTTP客户端控制台输出:

before request
finished

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接