Skip to content

Instantly share code, notes, and snippets.

@2minchul
Created December 4, 2019 05:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save 2minchul/6d344a0f1f85ead1530803df2e4f9894 to your computer and use it in GitHub Desktop.
Save 2minchul/6d344a0f1f85ead1530803df2e4f9894 to your computer and use it in GitHub Desktop.
Cancellation for http request using NewRequestWithContext in Golang
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