Home > Backend Development > Golang > How Can I Cancel a Long-Polling HTTP Request in Go?

How Can I Cancel a Long-Polling HTTP Request in Go?

Linda Hamilton
Release: 2024-12-01 00:10:15
Original
915 people have browsed it

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()
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template