How to set timeout for http.Get() requests in Golang?
HTTP Timeout
In Go, you can set a timeout for an http.Client by creating a custom http.Client with a Timeout field set to a time.Duration value, and then passing that custom http.Client to the http.Get() function. Here's an example:
Example
package main
import (
"net/http"
"time"
)
func main() {
client := &http.Client{
Timeout: 5 * time.Second,
}
_, err := client.Get("https://example.com")
if err != nil {
// handle error
}
// do something with response
}
HTTP timeout using Context
You can also use context package to set a timeout, Here is an example:
Example
package main
import (
"context"
"net/http"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
// handle error
}
req = req.WithContext(ctx)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
// do something with resp
}
Most Helpful This Week
How do you send an HTTP DELETE request in Go?
Launches 10 Goroutines and each goroutine adding 10 values to a Channel
How do you handle HTTP server health checks in Go?
How do you set headers in an HTTP response in Go?
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
Golang program for implementation of Interpolation Search
Most Helpful This Week
Regular expression to validate phone numberExample: How to use TeeReader from IO Package in Golang?Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.How to use a mutex to define critical sections of code and fix race conditions?Runtime package variablesConstructors in GolangUser Defined Function Types in GolangHow to check if a string contains a substring in Golang?Example to create custom errorHow to create thumbnail of an image?