Skip to content

Instantly share code, notes, and snippets.

@littlefuntik
Last active July 9, 2023 05:43
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save littlefuntik/37b04e1e97510877485ec6856ecdc33c to your computer and use it in GitHub Desktop.
Save littlefuntik/37b04e1e97510877485ec6856ecdc33c to your computer and use it in GitHub Desktop.
Go lang request timeouts example, DialContext, context.WithTimeout, http.Client, http.NewRequestWithContext
package main
import (
"context"
"io/ioutil"
"log"
"net"
"net/http"
"time"
)
// Connect timeout error:
// panic: Cannot do request: Get http://localhost:3000: dial tcp: i/o timeout
// Request timeout error:
// panic: Cannot do request: Get http://localhost:3000: context deadline exceeded
// Example output
// 2020/11/03 12:23:42 Do request
// 2020/11/03 12:23:43 Read body
// 2020/11/03 12:23:43 Read response took: 154.884µs
// 2020/11/03 12:23:43 {"ip":"*.*.*.*","country":"Ukraine","cc":"UA"}
func main() {
const ConnectMaxWaitTime = 1 * time.Second
const RequestMaxWaitTime = 5 * time.Second
client := http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: ConnectMaxWaitTime,
}).DialContext,
},
}
ctx, cancel := context.WithTimeout(context.Background(), RequestMaxWaitTime)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.myip.com", nil)
if err != nil {
log.Panicf("Cannot create request: %s\n", err)
}
log.Println("Do request")
rsp, err := client.Do(req)
if rsp != nil {
defer rsp.Body.Close()
}
if e,ok := err.(net.Error); ok && e.Timeout() {
log.Panicf("Do request timeout: %s\n", err)
} else if err != nil {
log.Panicf("Cannot do request: %s\n", err)
}
log.Println("Read body")
startRead := time.Now()
body, err := ioutil.ReadAll(rsp.Body)
if err != nil {
log.Panicf("Cannot read all response body: %s\n", err)
}
endRead := time.Now()
log.Printf("Read response took: %s\n", endRead.Sub(startRead))
log.Printf("%s\n", body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment