Skip to content

Instantly share code, notes, and snippets.

@kwoktung
Forked from 2minchul/main.go
Last active December 5, 2019 06:20
Show Gist options
  • Save kwoktung/6b0dcd485df68f4428b24a8bebee1af4 to your computer and use it in GitHub Desktop.
Save kwoktung/6b0dcd485df68f4428b24a8bebee1af4 to your computer and use it in GitHub Desktop.
Cancellation for http request using NewRequestWithContext in Golang
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