-
Notifications
You must be signed in to change notification settings - Fork 2
/
gandi.go
110 lines (84 loc) · 2.32 KB
/
gandi.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"github.com/pkg/errors"
)
type gandiClient struct {
Token string
}
// domainRecord represents a DNS Record
type domainRecord struct {
RrsetType string `json:"rrset_type,omitempty"`
RrsetTTL int `json:"rrset_ttl,omitempty"`
RrsetName string `json:"rrset_name,omitempty"`
RrsetHref string `json:"rrset_href,omitempty"`
RrsetValues []*net.IP `json:"rrset_values,omitempty"`
}
func (c *gandiClient) get(domain string, record string) ([]*domainRecord, error) {
url := fmt.Sprintf("https://api.gandi.net/v5/livedns/domains/%s/records/%s", domain, record)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "ApiKey "+c.Token)
req.Header.Set("Content-type", "application/json")
res, err := defaultHTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
records := make([]*domainRecord, 0)
err = json.Unmarshal(body, &records)
if err != nil {
return nil, errors.Wrapf(err, "failed to get %s/records/%s response=%s", domain, record, body)
}
return records, nil
}
func rrsetType(ip *net.IP) string {
if xx := ip.To4(); xx == nil {
return "AAAA"
}
return "A"
}
func (c *gandiClient) put(domain string, name string, ips []*net.IP, ttl int) error {
record := struct {
Items []*domainRecord `json:"items"`
}{Items: make([]*domainRecord, 0, 2)}
for _, ip := range ips {
item := &domainRecord{RrsetTTL: ttl, RrsetValues: []*net.IP{ip}, RrsetType: rrsetType(ip)}
record.Items = append(record.Items, item)
}
payload, err := json.Marshal(record)
if err != nil {
return err
}
url := fmt.Sprintf("https://api.gandi.net/v5/livedns/domains/%s/records/%s", domain, name)
req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Authorization", "ApiKey "+c.Token)
req.Header.Set("Content-type", "application/json")
res, err := defaultHTTP.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode >= 400 {
return fmt.Errorf("failed to perform PUT status=%d response=%s", res.StatusCode, body)
}
return nil
}