Context Timeout HTTP Client
Set timeouts on HTTP client requests using context for preventing hanging connections.
Code
package main
import ("context";"net/http";"time";"io")
func fetchWithTimeout(url string, timeout time.Duration) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil { return nil, err }
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}Report a problem with this exampleOpens a pre-filled issue on GitHub.