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
GO Program to Check Armstrong Number
Example of Sscan vs Sscanf vs Sscanln from FMT Package
How to build a map of struct and append values to it?
Program in Golang to print Pyramid of Numbers
Golang program for implementation of Floyd–Warshall Algorithm
Use Field Tags in the Definition of Struct Type
Most Helpful This Week
How to check if a string contains a white space in Golang?How to use a mutex to define critical sections of code and fix race conditions?Find element in a slice and move it to first position?Select single argument from all arguments of variadic functionReplace any non-alphanumeric character sequences with a dash using RegexRegular expression to validate email addressConvert Int data type to Int16 Int32 Int64Strip all white spaces, tabs, newlines from a stringHow to use for and foreach loop?Golang Get current Date and Time in EST, UTC and MST?