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

时间:2015-03-22 17:43:23

标签: go long-polling

我使用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 个答案:

答案 0 :(得分:15)

标准方法是使用类型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 mentioned,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 :(得分:11)

现在不推荐使用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)
// ...

答案 2 :(得分:6)

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

答案 3 :(得分:0)

@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 Server控制台打印:

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

答案 4 :(得分:0)

要添加将 context.Context 附加到 http 请求的其他答案,自 1.13 以来,我们有:

<块引用>

添加了一个新函数 NewRequestWithContext,它接受​​一个 Context 来控制创建的传出 Request 的整个生命周期,适用于 Client.Do 和 {{ 1}}。

https://golang.org/doc/go1.13#net/http

可以使用此函数来代替使用 Transport.RoundTripNewRequest

Request.WithContext

变成

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