Home > Backend Development > Golang > 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
Release: 2024-10-30 09:43:02
Original
735 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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