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 Program to print Floyd's triangle
Go program to find Name Server (NS) record of a domain
Find odd and even numbers using goroutines and channels
How do you handle HTTP server HTTP/2 in Go?
Golang program for implementation of Huffman Coding Algorithm
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
Most Helpful This Week
How to create thumbnail of an image?How to get Dimensions of an image type jpg jpeg png or gif ?How to use array in Go Programming Language?Simple example of Map initialization in GoHow to print struct variables data in Golang?How to Unmarshal nested JSON structure?Converting Int data type to Float in GoHow to add Watermark or Merge two image?Strip all white spaces, tabs, newlines from a stringHow to convert Boolean Type to String in Go?