Home >Backend Development >Golang >How can I effectively cancel HTTP requests in Go when a timeout occurs?
In your provided code, you have implemented a timeout mechanism using a select statement to handle either the result from the findCicCode() function or a timeout of 50 milliseconds. However, you expressed concerns about the potential for resource leakage if the HTTP calls continue to execute even after the timeout.
To address this issue, you can leverage the concept of context in Go. Context provides a way to associate context-specific values with goroutines and allows for cancelation. With context, you can cancel ongoing HTTP calls when a timeout occurs.
Here's an example of how you can implement context cancelation for HTTP requests:
<code class="go">package main import ( "context" "fmt" "net/http" "time" ) type Response struct { data interface{} status bool } func Find() (interface{}, bool) { ch := make(chan Response, 1) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() // Ensure cancelation when the function exits go func() { data, status := findCicCode(ctx) ch <- Response{data: data, status: status} }() select { case response := <-ch: return response.data, response.status case <-time.After(50 * time.Millisecond): return "Request timed out", false } } func main() { data, timedOut := Find() fmt.Println(data, timedOut) }</code>
In this modified code:
By using this approach, you ensure that any ongoing HTTP requests are canceled when the timeout is reached, preventing unnecessary resource consumption.
The above is the detailed content of How can I effectively cancel HTTP requests in Go when a timeout occurs?. For more information, please follow other related articles on the PHP Chinese website!