Created
December 4, 2019 05:06
-
-
Save 2minchul/6d344a0f1f85ead1530803df2e4f9894 to your computer and use it in GitHub Desktop.
Cancellation for http request using NewRequestWithContext in Golang
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" | |
"net/http" | |
"time" | |
) | |
func main() { | |
ctx := context.Background() | |
ctx, cancel := context.WithCancel(ctx) | |
req, _ := http.NewRequestWithContext(ctx, "GET", "http://httpbin.org/delay/3", nil) // it will return later 3 sec | |
client := &http.Client{} | |
go func() { | |
time.Sleep(time.Second * 2) | |
println("Cancel") | |
cancel() | |
}() | |
println("Do") | |
resp, err := client.Do(req) | |
println("Do finished") | |
if err != nil { | |
panic(err) // cancel caught | |
} | |
println(resp.StatusCode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment