💻 Tech
Performing http request in Go can include a context with a timeout to ensure that the process finishes within expected time and frees up resources.
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
// may return context deadline exceeded if the timeout is reached
if err != nil {
return err
}