-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
62 lines (58 loc) · 1.19 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"sync"
)
var client = http.Client{}
func callBoth(ctx context.Context, errVal string, slowURL string, fastURL string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
err := callServer(ctx, "slow", slowURL)
if err != nil {
cancel()
}
}()
go func() {
defer wg.Done()
err := callServer(ctx, "fast", fastURL+"?error="+errVal)
if err != nil {
cancel()
}
}()
wg.Wait()
fmt.Println("done with both")
}
func callServer(ctx context.Context, label string, url string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
fmt.Println(label, "request err:", err)
return err
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(label, "response err:", err)
return err
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(label, "read err:", err)
return err
}
result := string(data)
if result != "" {
fmt.Println(label, "result:", result)
}
if result == "error" {
fmt.Println("cancelling from", label)
return errors.New("error happened")
}
return nil
}