Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Last active April 19, 2017 08:55
Show Gist options
  • Save tkuchiki/97750e3de46e3c5ac6358ad5937a8cb5 to your computer and use it in GitHub Desktop.
Save tkuchiki/97750e3de46e3c5ac6358ad5937a8cb5 to your computer and use it in GitHub Desktop.
context.Deadline で HTTP Request で待たされても強制的にキャンセルする

http://localhost:9292 は sleep 10 しているので 10秒経たないとレスポンスを返さないとする。

$ time go run main.go
done
requested

real    0m1.319s
user    0m1.270s
sys     0m0.113s
package main
import (
"context"
"fmt"
"net/http"
"sync"
"time"
)
func main() {
client := http.DefaultClient
url := "http://localhost:9292/"
deadline := time.Now().Add(1 * time.Second)
ctxP, timeoutP := context.WithDeadline(context.Background(), deadline)
ctxC1, timeoutC1 := context.WithDeadline(ctxP, deadline)
defer timeoutP()
defer timeoutC1()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
loop:
for {
select {
case <-ctxP.Done():
fmt.Println("done")
break loop
default:
// do somthing
}
}
}()
go func() {
defer wg.Done()
loop:
for {
select {
case <-ctxC1.Done():
break loop
default:
req, _ := http.NewRequest("GET", url, nil)
resp, err := client.Do(req.WithContext(ctxC1))
if err == nil {
defer resp.Body.Close()
}
fmt.Println("requested")
}
}
}()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment