How to Abort a Go HTTP Client POST Request Before Completion?

Patricia Arquette
Release: 2024-11-27 07:50:09
Original
659 people have browsed it

How to Abort a Go HTTP Client POST Request Before Completion?

Aborting a Go HTTP Client POST Request Prematurely

In Go, the http.Client library is commonly used for client-side HTTP requests. When performing long-polling operations, it may be necessary to prematurely abort the request due to user actions or other events.

The standard approach to pre-empt or cancel a client-side request is by setting a timeout using http.Transport. However, this mechanism only allows for cancellation based on timeouts, not user-initiated actions.

A more flexible solution is to utilize the http.Request.WithContext function. This function allows the request to be associated with a context.Context. The context can then be canceled or set with a deadline, allowing for cancellation at any point.

To implement this approach:

  1. Create an http.Request as usual.
  2. Use req.WithContext(ctx) to associate the request with a context. The context can be created using context.WithDeadline or context.WithCancel.
  3. Use the modified request object (req) to make the request using the client.Do method.

Example:

import (
    "context"
    "net/http"
)

// Create a context with a user-specified timeout or cancellation.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() // Remember to cancel the context when done.

// Create an HTTP request.
req, err := http.NewRequest("POST", "http://example.com", nil)
if err != nil {
    // Handle error.
}

// Add headers or other request-specific information.

// Associate the request with the context.
req = req.WithContext(ctx)

// Perform the request.
resp, err := client.Do(req)
if err != nil {
    // Handle error.
}
// ... // Handle the response as usual.
Copy after login

Using this approach, the request will be automatically aborted if the context is canceled or if the deadline expires.

The above is the detailed content of How to Abort a Go HTTP Client POST Request Before Completion?. 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