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.
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 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3