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.
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>
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!