-
Notifications
You must be signed in to change notification settings - Fork 23
/
ip.go
84 lines (77 loc) · 1.8 KB
/
ip.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package ip
import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"time"
)
const DefaultTimeout = 10 * time.Second
type IPGetter struct {
ServiceURL string
GetIP func(url string, ctx context.Context) (string, error)
}
func HTTPGetBody(url string, ctx context.Context) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer res.Body.Close()
bz, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return bz, nil
}
func HTTPGetString(url string, ctx context.Context) (string, error) {
bz, err := HTTPGetBody(url, ctx)
if err != nil {
return "", err
}
return string(bz), err
}
func HTTPJSONGetField(field string) func(string, context.Context) (string, error) {
return func(url string, ctx context.Context) (string, error) {
body, err := HTTPGetBody(url, ctx)
if err != nil {
return "", err
}
m := map[string]string{}
err = json.Unmarshal(body, &m)
if err != nil {
return "", err
}
return m[field], err
}
}
func RunProviders(ipGetters []IPGetter, timeout time.Duration) (string, error) {
ch := make(chan string, len(ipGetters))
for _, ipGetter := range ipGetters {
url := ipGetter.ServiceURL
go func(url string, ipGetter IPGetter) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
ip, err := ipGetter.GetIP(url, ctx)
if err == nil {
ch <- ip
} else {
ch <- ""
}
}(url, ipGetter)
}
limit := len(ipGetters)/2 + 1
ipCount := map[string]int{}
for i := 0; i < len(ipGetters); i++ {
ip := <-ch
ipCount[ip]++
if len(ip) > 0 && ipCount[ip] >= limit {
return ip, nil
}
}
return "", errors.New("cannot get majority agree on the same IP")
}