There are several approaches to handle timeout errors in network operations in Go. Here are a few common techniques:
ctx, cancel := context.WithTimeout(context.Background(), time.Second) // Set timeout to 1 second
defer cancel() // Cancel the context to release resources
// Make the network request using the context
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://example.com", nil)
if err != nil {
// Handle error
log.Fatal(err)
}
// Perform the network operation
resp, err := http.DefaultClient.Do(req)
if err != nil {
if err == context.DeadlineExceeded {
// Timeout occurred
log.Fatal("Request timed out")
}
// Handle other errors
log.Fatal(err)
}
// Process the response
// ...
timeout := time.After(time.Second) // Set timeout to 1 second
// Make the network request
respCh := make(chan *http.Response, 1)
errCh := make(chan error, 1)
go func() {
resp, err := http.Get("http://example.com")
if err != nil {
errCh <- err
return
}
respCh <- resp
}()
// Wait for the network operation or timeout
select {
case resp := <-respCh:
// Process the response
case err := <-errCh:
// Handle error
case <-timeout:
// Timeout occurred
log.Fatal("Request timed out")
}
client := &http.Client{
Timeout: time.Second, // Set timeout to 1 second
}
// Make the network request
resp, err := client.Get("http://example.com")
if err != nil {
// Handle error
log.Fatal(err)
}
// Process the response
// ...
Choose the technique that best suits your use case and application requirements.