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 HTML parser
How to replace emoji characters in string using regex in Golang?
How to use function from another file golang?
URL parser in Golang
Closures Functions in Golang
Regular expression to validate phone number
Example: How to use TeeReader from IO Package in Golang?
How to get first and last element of slice in Golang?
Regular expression for matching HH:MM time format in Golang
How to create a photo gallery in Go?
Most Helpful This Week
How To Make HTTP Requests in Go?How to import and alias package names?How to rotate an image?Golang Convert String into Snake CaseHow to Remove duplicate values from Slice?Example: How to use ReadAtLeast from IO Package in Golang?Creating a Function in GolangGolang Get current Date and Time in EST, UTC and MST?How to convert Boolean Type to String in Go?Replace any non-alphanumeric character sequences with a dash using Regex