How to Prematurely Terminate an HTTP POST Request in Golang?

Linda Hamilton
Release: 2024-11-25 18:28:11
Original
405 people have browsed it

How to Prematurely Terminate an HTTP POST Request in Golang?

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

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!

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