-
-
Save kwoktung/6b0dcd485df68f4428b24a8bebee1af4 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" | |
"fmt" | |
"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 { | |
fmt.Println(err) // cancel caught | |
fmt.Println(ctx.Err()) | |
} | |
println(resp == nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment