Home >Backend Development >Golang >How Can I Prematurely Close Go HTTP Client POST Requests?

How Can I Prematurely Close Go HTTP Client POST Requests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 09:01:09290browse

How Can I Prematurely Close Go HTTP Client POST Requests?

Premature Closure of 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!

Statement:
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