Skip to content

Instantly share code, notes, and snippets.

@up1
Created April 16, 2019 07:22
Show Gist options
  • Save up1/bf4a3591597f499c3479cd3384253184 to your computer and use it in GitHub Desktop.
Save up1/bf4a3591597f499c3479cd3384253184 to your computer and use it in GitHub Desktop.
Go Request Timeout
package main
import (
"context"
"log"
"net/http"
"time"
)
func main() {
uri := "https://httpbin.org/delay/3"
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}
// Timeout = 100 ms
ctx, _ := context.WithTimeout(context.Background(), time.Millisecond*100)
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("http.DefaultClient.Do() failed with:\n'%s'\n", err)
}
defer resp.Body.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment