-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
getrecord.go
64 lines (55 loc) · 1.51 KB
/
getrecord.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
package namecom
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/qdm12/ddns-updater/internal/provider/errors"
)
func (p *Provider) getRecordID(ctx context.Context, client *http.Client,
recordType string) (recordID int, err error) {
u := &url.URL{
Scheme: "https",
Host: "api.name.com",
Path: fmt.Sprintf("/v4/domains/%s/records", p.domain),
User: url.UserPassword(p.username, p.token),
}
// by default GET request will return 1000 records.
request, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return 0, fmt.Errorf("creating http request: %w", err)
}
setHeaders(request)
response, err := client.Do(request)
if err != nil {
return 0, fmt.Errorf("doing http request: %w", err)
}
defer response.Body.Close()
switch response.StatusCode {
case http.StatusOK:
case http.StatusNotFound:
return 0, fmt.Errorf("%w", errors.ErrDomainNotFound)
default:
return 0, parseErrorResponse(response)
}
decoder := json.NewDecoder(response.Body)
var data struct {
Records []struct {
RecordID int `json:"id"`
Host string `json:"host"`
Type string `json:"type"`
} `json:"records"`
}
err = decoder.Decode(&data)
if err != nil {
return 0, fmt.Errorf("json decoding response body: %w", err)
}
for _, record := range data.Records {
if record.Host == p.host && record.Type == recordType {
return record.RecordID, nil
}
}
return 0, fmt.Errorf("%w: in %d record(s)",
errors.ErrRecordNotFound, len(data.Records))
}