-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfetchers_test.go
61 lines (52 loc) · 1.37 KB
/
fetchers_test.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
package ipfilterware_test
import (
"bytes"
"context"
"io"
"net/http"
)
// Copy-paste friendly fetchers.
// Doer represents HTTP client.
type Doer interface {
Do(req *http.Request) (resp *http.Response, err error)
}
// FetchCloudflareIPv4 from https://www.cloudflare.com/ips-v4
func FetchCloudflareIPv4(ctx context.Context, client Doer) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.cloudflare.com/ips-v4", nil)
if err != nil {
return nil, err
}
return fetchAndSplit(client, req)
}
// FetchCloudflareIPv6 from https://www.cloudflare.com/ips-v6
func FetchCloudflareIPv6(ctx context.Context, client Doer) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.cloudflare.com/ips-v6", nil)
if err != nil {
return nil, err
}
return fetchAndSplit(client, req)
}
func fetchAndSplit(client Doer, req *http.Request) ([]string, error) {
body, err := fetch(client, req)
if err != nil {
return nil, err
}
lines := bytes.Split(body, []byte{'\n'})
ips := make([]string, 0, len(lines))
for _, line := range lines {
ips = append(ips, string(line))
}
return ips, nil
}
func fetch(client Doer, req *http.Request) ([]byte, error) {
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}