Home  >  Article  >  Backend Development  >  How to Prevent Goroutine Leaks and Cancel HTTP Requests within a Timeout?

How to Prevent Goroutine Leaks and Cancel HTTP Requests within a Timeout?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 09:43:02643browse

How to Prevent Goroutine Leaks and Cancel HTTP Requests within a Timeout?

Goroutine Timeout with Concurrency Control

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!

Statement:
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