-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
89 lines (71 loc) · 2.04 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
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
package main
import (
"errors"
"io"
"net"
"net/http"
"net/url"
"strings"
)
type DynClient struct {
client *http.Client
userAgent string
}
func NewDynClient(userAgent string) *DynClient {
return &DynClient{&http.Client{}, userAgent}
}
func (c *DynClient) Update(record Record, ip net.IP) (string, string, error) {
record.UpdateUrl = strings.ReplaceAll(record.UpdateUrl, "<ipaddr>", ip.String())
record.Body = strings.ReplaceAll(record.Body, "<ipaddr>", ip.String())
parsedUrl, err := url.Parse(record.UpdateUrl)
if err != nil {
return "", "", err
}
parsedUrl.User = url.UserPassword(parsedUrl.User.Username(), "***")
urlWithoutPassword := strings.ReplaceAll(parsedUrl.String(), "%2A%2A%2A", "***")
method := record.Method
if method == "" {
method = "GET"
}
request, err := http.NewRequest(method, record.UpdateUrl, strings.NewReader(record.Body))
if err != nil {
return "", urlWithoutPassword, err
}
request.Header.Set("User-Agent", c.userAgent)
for _, header := range record.Headers {
name, value, found := strings.Cut(header, ": ")
if !found {
return "", urlWithoutPassword, errors.New("Invalid header: " + header)
}
request.Header.Set(name, value)
}
response, err := c.client.Do(request)
if err != nil {
return "", urlWithoutPassword, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return "", urlWithoutPassword, err
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return string(body), urlWithoutPassword, errors.New(method + " " + urlWithoutPassword + " returned " + response.Status + ": " + string(body))
}
return string(body), urlWithoutPassword, nil
}
func (c *DynClient) GetExternalIp(ipRetrieveUrl string) (net.IP, error) {
request, err := http.NewRequest("GET", ipRetrieveUrl, nil)
if err != nil {
return nil, err
}
response, err := c.client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
return net.ParseIP(string(body)), nil
}