Home > Backend Development > Golang > How to Prevent HTTP Requests from Continuing After Timeout in a Goroutine?

How to Prevent HTTP Requests from Continuing After Timeout in a Goroutine?

DDD
Release: 2024-11-01 05:43:02
Original
638 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template