-
Notifications
You must be signed in to change notification settings - Fork 18.3k
Closed
Labels
Description
tl;dr
From the net/http
package, export errTimeout
, errRequestCanceled
, and errRequestCanceledConn
.
Request timeout
When making an http
request with a timeout, the http client.Do
throws an unexported errTimeout
. This makes parsing the error problematic. For example:
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func main() {
client := http.DefaultClient
request, _ := http.NewRequest("GET", "https://google.com", nil)
ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
request = request.WithContext(ctx)
if response, err := client.Do(request); err != nil {
// Untyped error. Have to scrape error message to find out if it's a
// timeout.
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
}
}
It would be safer to export this error. For example:
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func main() {
client := http.DefaultClient
request, _ := http.NewRequest("GET", "https://google.com", nil)
ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
request = request.WithContext(ctx)
if response, err := client.Do(request); err != nil {
// Untyped error. Have to scrape error message to find out if it's a
// timeout.
if err == http.ErrTimeout {
// Retry request with a back off.
}
} else {
fmt.Println(response.StatusCode)
}
}