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
Converting Int data type to Float in Go
Golang Web Server Example
Example: ReadAll, ReadDir, and ReadFile from IO Package
Use Field Tags in the Definition of Struct Type
Go program to find CNAME record of a domain
How to change slice item value in Golang?
How to remove multiple spaces in a string in GoLang?
How to create an empty Slice in Golang?
Modernizing Legacy Applications: Critical Tips for Organizational Upgrades
How to check specific field exist in struct?
Most Helpful This Week
Regular expression to validate email addressRegular expression to extract all Non-Alphanumeric Characters from a StringHow to create Map using the make function in Go?How to convert Boolean Type to String in Go?Golang String ConcatenationHow to reads and decodes JSON values from an input stream?Golang download image from given URLHow to count number of repeating words in a given String?How to print string with double quote in Go?How to import structs from another package in Go?