type Response struct {
data interface{}
status bool
}
func Find() (interface{}, bool) {
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 <-time.After(50 * time.Millisecond):
return "Request timed out", false
}
}
So, I have above function. Basically findCicCode()
function call makes 3 http calls internally to external services. I have added combined timeout here for those 3 http calls. Can't put individual timeout in my case. But It still makes api calls in background if it exceeds timeout.
I am not sure if there is goroutine leak here. Is there a way to cancel those https requests if there is timeout?
You control cancelation of http requests with a context.Context
.
// create a timeout or cancelation context to suit your requirements
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
req, err := http.NewRequest("GET", location, nil)
// add the context to each request and they will be canceled in unison
resp, err := http.Do(req.WithContext(ctx))