How to Set Timeout for http.Get Requests in Go
Created
Modified
Using http.Client.Timeout Field
Timeout specifies a time limit for requests made by this Client. The timeout includes connection time, any redirects, and reading the response body.
See the following example:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
client := http.Client{
Timeout: 2 * time.Second,
}
resp, err := client.Get("https://google.com")
fmt.Println(resp, err)
}
context deadline exceeded (Client.Timeout exceeded while awaiting headers)
Using context.WithTimeout Function
If you want to do it per request, err handling ignored for brevity:
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func main() {
ctx, cncl := context.WithTimeout(context.Background(), 3*time.Second)
defer cncl()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://google.com", nil)
resp, err := http.DefaultClient.Do(req)
fmt.Println(resp, err)
}
context deadline exceeded