http://localhost:9292 は sleep 10 しているので 10秒経たないとレスポンスを返さないとする。
$ time go run main.go
done
requested
real 0m1.319s
user 0m1.270s
sys 0m0.113s
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() | |
} |