/
client.go
241 lines (185 loc) · 5.36 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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package internal
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)
const apiBaseURL = "https://admin.vshosting.cloud/clouddns"
const authorizationHeader = "Authorization"
// Client handles all communication with CloudDNS API.
type Client struct {
clientID string
email string
password string
ttl int
apiBaseURL *url.URL
loginURL *url.URL
HTTPClient *http.Client
}
// NewClient returns a Client instance configured to handle CloudDNS API communication.
func NewClient(clientID, email, password string, ttl int) *Client {
baseURL, _ := url.Parse(apiBaseURL)
loginBaseURL, _ := url.Parse(loginURL)
return &Client{
clientID: clientID,
email: email,
password: password,
ttl: ttl,
apiBaseURL: baseURL,
loginURL: loginBaseURL,
HTTPClient: &http.Client{Timeout: 5 * time.Second},
}
}
// AddRecord is a high level method to add a new record into CloudDNS zone.
func (c *Client) AddRecord(ctx context.Context, zone, recordName, recordValue string) error {
domain, err := c.getDomain(ctx, zone)
if err != nil {
return err
}
record := Record{DomainID: domain.ID, Name: recordName, Value: recordValue, Type: "TXT"}
err = c.addTxtRecord(ctx, record)
if err != nil {
return err
}
return c.publishRecords(ctx, domain.ID)
}
// DeleteRecord is a high level method to remove a record from zone.
func (c *Client) DeleteRecord(ctx context.Context, zone, recordName string) error {
domain, err := c.getDomain(ctx, zone)
if err != nil {
return err
}
record, err := c.getRecord(ctx, domain.ID, recordName)
if err != nil {
return err
}
err = c.deleteRecord(ctx, record)
if err != nil {
return err
}
return c.publishRecords(ctx, domain.ID)
}
func (c *Client) addTxtRecord(ctx context.Context, record Record) error {
endpoint := c.apiBaseURL.JoinPath("record-txt")
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, record)
if err != nil {
return err
}
return c.do(req, nil)
}
func (c *Client) deleteRecord(ctx context.Context, record Record) error {
endpoint := c.apiBaseURL.JoinPath("record", record.ID)
req, err := newJSONRequest(ctx, http.MethodDelete, endpoint, nil)
if err != nil {
return err
}
return c.do(req, nil)
}
func (c *Client) getDomain(ctx context.Context, zone string) (Domain, error) {
searchQuery := SearchQuery{
Search: []Search{
{Name: "clientId", Operator: "eq", Value: c.clientID},
{Name: "domainName", Operator: "eq", Value: zone},
},
}
endpoint := c.apiBaseURL.JoinPath("domain", "search")
req, err := newJSONRequest(ctx, http.MethodPost, endpoint, searchQuery)
if err != nil {
return Domain{}, err
}
var result SearchResponse
err = c.do(req, &result)
if err != nil {
return Domain{}, err
}
if len(result.Items) == 0 {
return Domain{}, fmt.Errorf("domain not found: %s", zone)
}
return result.Items[0], nil
}
func (c *Client) getRecord(ctx context.Context, domainID, recordName string) (Record, error) {
endpoint := c.apiBaseURL.JoinPath("domain", domainID)
req, err := newJSONRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return Record{}, err
}
var result DomainInfo
err = c.do(req, &result)
if err != nil {
return Record{}, err
}
for _, record := range result.LastDomainRecordList {
if record.Name == recordName && record.Type == "TXT" {
return record, nil
}
}
return Record{}, fmt.Errorf("record not found: domainID %s, name %s", domainID, recordName)
}
func (c *Client) publishRecords(ctx context.Context, domainID string) error {
endpoint := c.apiBaseURL.JoinPath("domain", domainID, "publish")
payload := DomainInfo{SoaTTL: c.ttl}
req, err := newJSONRequest(ctx, http.MethodPut, endpoint, payload)
if err != nil {
return err
}
return c.do(req, nil)
}
func (c *Client) do(req *http.Request, result any) error {
at := getAccessToken(req.Context())
if at != "" {
req.Header.Set(authorizationHeader, "Bearer "+at)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode/100 != 2 {
return parseError(req, resp)
}
if result == nil {
return nil
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return errutils.NewReadResponseError(req, resp.StatusCode, err)
}
err = json.Unmarshal(raw, result)
if err != nil {
return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}
return nil
}
func newJSONRequest(ctx context.Context, method string, endpoint *url.URL, payload any) (*http.Request, error) {
buf := new(bytes.Buffer)
if payload != nil {
err := json.NewEncoder(buf).Encode(payload)
if err != nil {
return nil, fmt.Errorf("failed to create request JSON body: %w", err)
}
}
req, err := http.NewRequestWithContext(ctx, method, endpoint.String(), buf)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
req.Header.Set("Accept", "application/json")
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}
func parseError(req *http.Request, resp *http.Response) error {
raw, _ := io.ReadAll(resp.Body)
var response APIError
err := json.Unmarshal(raw, &response)
if err != nil {
return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw)
}
return fmt.Errorf("[status code %d] %w", resp.StatusCode, response.Error)
}