Home >Backend Development >Golang >How to Prevent HTTP Requests from Continuing After Timeout in a Goroutine?
Goroutine Timeout
The provided function, Find(), uses a goroutine to make a series of HTTP requests and handle their responses. However, the concern is that these requests continue in the background even if they exceed the specified timeout.
Potential Goroutine Leak
It's unlikely that there is a goroutine leak in the code. When the Find() function returns a timeout, the main goroutine continues and the background goroutine is essentially abandoned.
HTTP Request Cancelation
To avoid making requests after a timeout, the solution is to use a context.Context for each HTTP request. A context allows you to cancel the request if a timeout occurs.
<code class="go">func Find() (interface{}, bool) { ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() ch := make(chan Response, 1) go func() { data, status := findCicCode() ch <- Response{data: data, status: status} }() select { case response := <-ch: return response.data, response.status case <-ctx.Done(): return "Request timed out", false } }</code>
When the timeout occurs, calling cancel() will cancel all the HTTP requests created within the ctx. This prevents any further processing or resources being consumed by those requests.
The above is the detailed content of How to Prevent HTTP Requests from Continuing After Timeout in a Goroutine?. For more information, please follow other related articles on the PHP Chinese website!