-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
client.go
97 lines (78 loc) · 2.29 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
90
91
92
93
94
95
96
97
package easydns
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path"
)
const defaultEndpoint = "https://rest.easydns.net"
type zoneRecord struct {
ID string `json:"id,omitempty"`
Domain string `json:"domain"`
Host string `json:"host"`
TTL string `json:"ttl"`
Prio string `json:"prio"`
Type string `json:"type"`
Rdata string `json:"rdata"`
LastMod string `json:"last_mod,omitempty"`
Revoked int `json:"revoked,omitempty"`
NewHost string `json:"new_host,omitempty"`
}
type addRecordResponse struct {
Msg string `json:"msg"`
Tm int `json:"tm"`
Data zoneRecord `json:"data"`
Status int `json:"status"`
}
func (d *DNSProvider) addRecord(domain string, record interface{}) (string, error) {
pathAdd := path.Join("/zones/records/add", domain, "TXT")
response := &addRecordResponse{}
err := d.doRequest(http.MethodPut, pathAdd, record, response)
if err != nil {
return "", err
}
recordID := response.Data.ID
return recordID, nil
}
func (d *DNSProvider) deleteRecord(domain, recordID string) error {
pathDelete := path.Join("/zones/records", domain, recordID)
return d.doRequest(http.MethodDelete, pathDelete, nil, nil)
}
func (d *DNSProvider) doRequest(method, resource string, requestMsg, responseMsg interface{}) error {
reqBody := &bytes.Buffer{}
if requestMsg != nil {
err := json.NewEncoder(reqBody).Encode(requestMsg)
if err != nil {
return err
}
}
endpoint, err := d.config.Endpoint.Parse(resource + "?format=json")
if err != nil {
return err
}
request, err := http.NewRequest(method, endpoint.String(), reqBody)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.SetBasicAuth(d.config.Token, d.config.Key)
response, err := d.config.HTTPClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("%d: failed to read response body: %w", response.StatusCode, err)
}
return fmt.Errorf("%d: request failed: %v", response.StatusCode, string(body))
}
if responseMsg != nil {
return json.NewDecoder(response.Body).Decode(responseMsg)
}
return nil
}