Premature Termination of an HTTP POST Request in Golang
In the context of implementing a long-polling client using http.Client, the need frequently arises to prematurely close or cancel an HTTP POST request. While the traditional approach involved closing the response body (resp.Body.Close()) in a separate goroutine, it introduces complications as the client is typically blocked while reading the response.
However, the current preferred strategy for request cancellation involves the use of a context with deadlines or that can be canceled as needed. This is achieved through the http.Request.WithContext method.
Here's how you can incorporate this strategy into your code:
import ( "context" "net/http" ) // ... // Create a context with a deadline or that can be canceled ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() req, err := http.NewRequest("POST", "http://example.com", bytes.NewBuffer(jsonPostBytes)) // ... // Add the context to the request req = req.WithContext(ctx) // Perform the request resp, err := client.Do(req)
By setting the context on the request, any subsequent operations on that request will respect the deadline or cancellation state of that context. For instance, if the context is canceled before the request is complete, the underlying transport will receive an error and the request will be aborted. This provides a clear and concise mechanism for prematurely terminating an HTTP POST request from the client-side.
The above is the detailed content of How to Prematurely Terminate an HTTP POST Request in Golang?. For more information, please follow other related articles on the PHP Chinese website!