Home >Backend Development >Golang >How to Prevent Goroutine Leaks and Cancel HTTP Requests within a Timeout?
In the provided code, you have implemented a function, Find(), that utilizes a goroutine (go func() statement) for asynchronous data retrieval using findCicCode(). You have set a timeout of 50 milliseconds to receive the response from the goroutine.
However, you are concerned about potential goroutine leaks if the timeout is exceeded. Additionally, you would like to be able to cancel the HTTP requests made by findCicCode() when the timeout occurs.
Goroutine Leak Prevention
To handle goroutine leaks, it is essential to ensure that any goroutine created in a specific scope is terminated before the scope ends. In this case, it is important to cancel the goroutine within the select statement when the timeout is reached:
<code class="go">case <-time.After(50 * time.Millisecond): // Cancel the goroutine to prevent a potential leak close(ch) return "Request timed out", false</code>
HTTP Request Cancellation
To cancel HTTP requests within the goroutine, you can leverage the context.Context and context.CancelFunc provided by the Go standard library:
<code class="go">// Create a context with a timeout of 50 milliseconds ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() // Execute the findCicCode() function within this context data, status := findCicCodeWithContext(ctx) // If the context is canceled (timeout), the HTTP requests will be aborted</code>
The above is the detailed content of How to Prevent Goroutine Leaks and Cancel HTTP Requests within a Timeout?. For more information, please follow other related articles on the PHP Chinese website!