Home >Backend Development >Golang >How Can I Cancel a Long-Polling HTTP Request in Go?
Cancelling a Long-Polling Request in Golang
When implementing a client-side long-poll using http.Client, it is often desirable to have the ability to cancel the request prematurely. This could be achieved by manually calling resp.Body.Close() from a separate goroutine, but it is not a standard and elegant solution.
Cancellation Using Request Context
A more idiomatic way to cancel an HTTP request in Golang is by using the request context. By passing a context with a deadline or a cancel function, the request can be cancelled from the client side. The following code demonstrates how to use the request context to cancel a long-polling request:
import ( "context" "net/http" ) func main() { // Create a new HTTP client with a custom transport. client := &http.Client{ Transport: &http.Transport{ // Set a timeout for the request. Dial: (&net.Dialer{Timeout: 5 * time.Second}).Dial, TLSHandshakeTimeout: 5 * time.Second, }, } // Create a new request with a context that can be cancelled. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) req, err := http.NewRequest("POST", "http://example.com", nil) if err != nil { panic(err) } req = req.WithContext(ctx) // Start the request in a goroutine and cancel it after 5 seconds. go func() { _, err := client.Do(req) if err != nil { // Handle the canceled error. } }() time.Sleep(5 * time.Second) cancel() }
When the cancel() function is called, the request will be cancelled and the Dial and TLSHandshakeTimeout specified in the transport will be respected.
The above is the detailed content of How Can I Cancel a Long-Polling HTTP Request in Go?. For more information, please follow other related articles on the PHP Chinese website!