-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
200 lines (170 loc) · 3.87 KB
/
http.go
File metadata and controls
200 lines (170 loc) · 3.87 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package checkhost
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type HTTPResultItem struct {
Success bool
Time float64
Message string
Code string
IP string
}
type HTTPResult map[string]*HTTPResultItem
type CheckHTTPResponse struct {
OK int `json:"ok"`
RequestID string `json:"request_id"`
PermanentLink string `json:"permanent_link"`
Nodes map[string][]string `json:"nodes"`
}
func (c *Client) CheckHTTP(d RequestData) (*CheckHTTPResponse, error) {
var reqData string
if len(d.Nodes) != 0 {
reqData = "node=" + strings.Join(d.Nodes, "&node=")
} else if d.MaxNodes != 0 {
reqData = fmt.Sprintf("max_nodes=%d", d.MaxNodes)
} else {
reqData = "max_nodes=3"
}
req, _ := http.NewRequest(
http.MethodGet,
fmt.Sprintf("%s/check-http?host=%s&%s", c.baseURL, url.QueryEscape(d.Host), reqData),
nil,
)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result CheckHTTPResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("invalid JSON: %v\nBody: %s", err, string(body))
}
return &result, nil
}
func (c *Client) HTTPResult(requestID string) (HTTPResult, error) {
urlStr := fmt.Sprintf("%s/check-result/%s", c.baseURL, requestID)
req, _ := http.NewRequest(http.MethodGet, urlStr, nil)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result HTTPResult
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("invalid JSON: %v\nBody: %s", err, string(body))
}
return result, nil
}
func (c *Client) WaitHTTPResult(requestID string, timeout, interval time.Duration) (HTTPResult, error) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
res, err := c.HTTPResult(requestID)
if err != nil {
return nil, err
}
done := true
for _, v := range res {
if v == nil || !v.Success && v.Message == "" {
done = false
break
}
}
if done {
return res, nil
}
time.Sleep(interval)
}
return nil, ErrTimeout
}
func (r *HTTPResultItem) UnmarshalJSON(data []byte) error {
var raw []any
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
if len(raw) == 0 {
return nil
}
if len(raw) > 0 {
switch v := raw[0].(type) {
case float64:
r.Success = v == 1
case int:
r.Success = v == 1
case bool:
r.Success = v
}
}
if len(raw) > 1 {
switch v := raw[1].(type) {
case float64:
r.Time = v
case int:
r.Time = float64(v)
}
}
if len(raw) > 2 {
if s, ok := raw[2].(string); ok {
r.Message = s
}
}
if len(raw) > 3 {
if s, ok := raw[3].(string); ok {
r.Code = s
}
}
if len(raw) > 4 {
if s, ok := raw[4].(string); ok {
r.IP = s
}
}
return nil
}
func (r *HTTPResult) UnmarshalJSON(data []byte) error {
raw := map[string]json.RawMessage{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
res := make(HTTPResult)
for node, rawNode := range raw {
if string(rawNode) == "null" {
res[node] = nil
continue
}
var lists [][]json.RawMessage
if err := json.Unmarshal(rawNode, &lists); err != nil {
return fmt.Errorf("failed to unmarshal node %s: %w", node, err)
}
if len(lists) == 0 || len(lists[0]) == 0 {
res[node] = nil
continue
}
arr := lists[0]
var buf bytes.Buffer
buf.WriteByte('[')
for j, part := range arr {
if j > 0 {
buf.WriteByte(',')
}
buf.Write(part)
}
buf.WriteByte(']')
item := &HTTPResultItem{}
if err := item.UnmarshalJSON(buf.Bytes()); err != nil {
return fmt.Errorf("failed to unmarshal node %s: %w", node, err)
}
res[node] = item
}
*r = res
return nil
}