Home >Backend Development >Golang >How Can I Prematurely Close Go HTTP Client POST Requests?
When working with HTTP long-polls using the http.Client, it may be necessary to terminate the request prematurely from the client-side. Historically, resp.Body.Close() could be used, but it required a separate goroutine to execute.
Current Solution: Context-based Cancellation
To resolve this issue, Go now recommends using http.Request.WithContext to pass a context with a deadline or cancelation mechanism. This eliminates the need for an additional goroutine and provides a cleaner, standardized approach.
Example
req, err := http.NewRequest("GET", "http://example.com", nil) req = req.WithContext(ctx) // Pass the context with deadline or cancelation mechanism resp, err := client.Do(req)
This approach provides greater control over request cancellation, allowing it to be triggered based on user actions or other application logic, not just timeouts.
The above is the detailed content of How Can I Prematurely Close Go HTTP Client POST Requests?. For more information, please follow other related articles on the PHP Chinese website!