How to prevent goroutine leaks and cancel HTTP requests when a timeout occurs?

Linda Hamilton
Release: 2024-10-31 08:22:02
Original
562 people have browsed it

How to prevent goroutine leaks and cancel HTTP requests when a timeout occurs?

Goroutine Timeout and Cancellation

The provided code defines a Find() function that attempts to obtain data from an external service via HTTP calls and times out after a specified duration. However, the concern raised is whether there is a potential for goroutine leaks and if there's a way to cancel the HTTP requests when the timeout occurs.

Context-based Cancellation

To effectively control the cancellation of HTTP requests, the context.Context mechanism can be utilized. By utilizing a context with a timeout, you can ensure that all HTTP requests associated with that context will be terminated when the timeout is reached.

The following code exemplifies how to implement context-based cancellation:

<code class="go">// create a timeout or cancelation context to suit your requirements
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

req, err := http.NewRequest("GET", location, nil)

// add the context to each request and they will be canceled in unison
resp, err := http.Do(req.WithContext(ctx))</code>
Copy after login

Within this code, ctx specifies the timeout or cancellation criteria, and defer cancel() guarantees that the context is always canceled when the function returns. By adding the context to each request via req.WithContext(ctx), all requests will be canceled simultaneously when the timeout expires.

This approach ensures that the goroutines responsible for making the HTTP requests will be terminated when the timeout occurs, preventing goroutine leaks and ensuring that the system promptly responds to timeouts.

The above is the detailed content of How to prevent goroutine leaks and cancel HTTP requests when a timeout occurs?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!