-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp.go
More file actions
104 lines (86 loc) · 2.48 KB
/
Copy pathhttp.go
File metadata and controls
104 lines (86 loc) · 2.48 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package f35
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
const whoisURL = "https://api.ipiz.net"
type whoisResponse struct {
OrgName string `json:"org_name"`
Country string `json:"country"`
Status string `json:"status"`
}
func doHTTPCheck(client *http.Client, method string, targetURL string, timeout time.Duration, drainBody bool) (int64, bool) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, targetURL, nil)
if err != nil {
return 0, false
}
req.Header.Set("Connection", "close")
startedAt := time.Now()
resp, err := client.Do(req)
if err != nil {
return 0, false
}
defer resp.Body.Close()
if drainBody {
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
return 0, false
}
}
return time.Since(startedAt).Milliseconds(), true
}
func doUploadCheck(client *http.Client, targetURL string, timeout time.Duration, payload []byte) (int64, bool) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(payload))
if err != nil {
return 0, false
}
req.Header.Set("Connection", "close")
req.Header.Set("Content-Type", "application/octet-stream")
startedAt := time.Now()
resp, err := client.Do(req)
if err != nil {
return 0, false
}
defer resp.Body.Close()
return time.Since(startedAt).Milliseconds(), true
}
func lookupResolverInfo(client *http.Client, resolverHost string, timeout time.Duration) (int64, string, string, bool) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, whoisURL+"/"+resolverHost, nil)
if err != nil {
return 0, "unknown", "unknown", false
}
req.Header.Set("Connection", "close")
startedAt := time.Now()
resp, err := client.Do(req)
if err != nil {
return 0, "unknown", "unknown", false
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, "unknown", "unknown", false
}
var data whoisResponse
if err := json.Unmarshal(body, &data); err != nil || strings.TrimSpace(data.Status) != "ok" {
return 0, "unknown", "unknown", false
}
org := strings.TrimSpace(data.OrgName)
if org == "" {
org = "unknown"
}
country := strings.TrimSpace(data.Country)
if country == "" {
country = "unknown"
}
return time.Since(startedAt).Milliseconds(), org, country, true
}