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
Golang Read Write Create and Delete text file
How to read names of all files and folders in current directory?
How to use wildcard or a variable in our URL for complex routing?
Higher Order Functions in Golang
How to extract text from between html tag using Regular Expressions in Golang?
How to iterate over an Array using for loop?
Most Helpful This Week
How to check if a string contains only letters in Golang?Regular expression to validate the date format in "dd/mm/yyyy"Various examples of Carbon date-time package in GolangGolang Read Write Create and Delete text fileExample Function that takes an interface type as value and pointer?Example to handle GET and POST request in GolangRegular expression to validate phone numberHow to check string contains uppercase lowercase character in Golang?Various examples of printing and formatting in GolangThe return values of a function can be named in Golang