-
-
Save junftnt/7645db10e39ae9027bd2782b1be094f4 to your computer and use it in GitHub Desktop.
http request with context in Go
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" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "time" | |
| ) | |
| func main() { | |
| req, err := http.NewRequest("GET", "http://www.yahoo.co.jp", nil) | |
| if err != nil { | |
| log.Fatalf("%v", err) | |
| } | |
| ctx, cancel := context.WithTimeout(req.Context(), 1*time.Millisecond) | |
| defer cancel() | |
| req = req.WithContext(ctx) | |
| client := http.DefaultClient | |
| res, err := client.Do(req) | |
| if err != nil { | |
| log.Fatalf("%v", err) | |
| } | |
| fmt.Printf("%v\n", res.StatusCode) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment