Created
April 16, 2019 07:22
-
-
Save up1/bf4a3591597f499c3479cd3384253184 to your computer and use it in GitHub Desktop.
Go Request Timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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