-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathpowerdns.go
240 lines (198 loc) · 5.37 KB
/
powerdns.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
package powerdns
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
)
// NewOption is a functional option for New.
type NewOption func(*Client)
// WithHeaders is an option for New to set HTTP client headers.
func WithHeaders(headers map[string]string) NewOption {
return func(client *Client) {
client.Headers = headers
}
}
// WithHTTPClient is an option for New to set an HTTP client.
func WithHTTPClient(httpClient *http.Client) NewOption {
return func(client *Client) {
client.httpClient = httpClient
}
}
// WithAPIKey is an option for New to set the API key.
func WithAPIKey(key string) NewOption {
return func(client *Client) {
client.apiKey = &key
}
}
type service struct {
client *Client
}
// Client configuration structure
type Client struct {
Scheme string
Hostname string
Port string
VHost string
Headers map[string]string
httpClient *http.Client
apiKey *string
common service // Reuse a single struct instead of allocating one for each service on the heap
Config *ConfigService
Cryptokeys *CryptokeysService
Records *RecordsService
Servers *ServersService
Statistics *StatisticsService
Zones *ZonesService
// Deprecated: Use TSIGKeys instead. TSIGKey will be removed with the next major version.
TSIGKey *TSIGKeysService
TSIGKeys *TSIGKeysService
}
// logFatalf makes log.Fatalf testable
var logFatalf = log.Fatalf
// NewClient initializes a new client instance.
//
// Deprecated: Use New with functional options instead. NewClient will be removed with the next major version.
func NewClient(baseURL string, vHost string, headers map[string]string, httpClient *http.Client) *Client {
effectiveHttpClient := httpClient
if httpClient == nil {
effectiveHttpClient = http.DefaultClient
}
return New(baseURL, vHost, WithHeaders(headers), WithHTTPClient(effectiveHttpClient))
}
// New initializes a new client instance.
func New(baseURL string, vHost string, options ...NewOption) *Client {
scheme, hostname, port, err := parseBaseURL(baseURL)
if err != nil {
logFatalf("%s is not a valid url: %v", baseURL, err)
}
client := &Client{
Scheme: scheme,
Hostname: hostname,
Port: port,
VHost: parseVHost(vHost),
httpClient: http.DefaultClient,
}
client.common.client = client
client.Config = (*ConfigService)(&client.common)
client.Cryptokeys = (*CryptokeysService)(&client.common)
client.Records = (*RecordsService)(&client.common)
client.Servers = (*ServersService)(&client.common)
client.Statistics = (*StatisticsService)(&client.common)
client.Zones = (*ZonesService)(&client.common)
client.TSIGKeys = (*TSIGKeysService)(&client.common)
client.TSIGKey = client.TSIGKeys
for _, option := range options {
option(client)
}
return client
}
func parseBaseURL(baseURL string) (string, string, string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", "", "", err
}
hp := strings.Split(u.Host, ":")
hostname := hp[0]
var port string
if len(hp) > 1 {
port = hp[1]
} else {
if u.Scheme == "https" {
port = "443"
} else {
port = "80"
}
}
return u.Scheme, hostname, port, nil
}
func parseVHost(vHost string) string {
if vHost == "" {
return "localhost"
}
return vHost
}
func generateAPIURL(scheme, hostname, port, path string, query *url.Values) url.URL {
u := url.URL{}
u.Scheme = scheme
u.Host = fmt.Sprintf("%s:%s", hostname, port)
u.Path = fmt.Sprintf("/api/v1/%s", path)
if query != nil {
u.RawQuery = query.Encode()
}
return u
}
func trimDomain(domain string) string {
return strings.TrimSuffix(domain, ".")
}
func makeDomainCanonical(domain string) string {
return fmt.Sprintf("%s.", trimDomain(domain))
}
func (p *Client) newRequest(ctx context.Context, method string, path string, query *url.Values, body interface{}) (*http.Request, error) {
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
_ = json.NewEncoder(buf).Encode(body)
}
apiURL := generateAPIURL(p.Scheme, p.Hostname, p.Port, path, query)
req, err := http.NewRequestWithContext(ctx, method, apiURL.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "go-powerdns")
if body != nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
}
if p.apiKey != nil {
req.Header.Set("X-API-Key", *p.apiKey)
}
for key, value := range p.Headers {
req.Header.Set(key, value)
}
return req, nil
}
func (p *Client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := p.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == 401 {
return resp, &Error{
Status: resp.Status,
StatusCode: resp.StatusCode,
Message: "Unauthorized",
}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
defer func() {
_ = resp.Body.Close()
}()
var message string
if resp.Header.Get("Content-Type") == "application/json" {
apiError := new(Error)
_ = json.NewDecoder(resp.Body).Decode(&apiError)
message = apiError.Message
} else {
messageBytes, _ := io.ReadAll(resp.Body)
message = string(messageBytes)
}
return resp, &Error{
Status: resp.Status,
StatusCode: resp.StatusCode,
Message: message,
}
}
if v != nil && resp.StatusCode != http.StatusNoContent {
defer func() {
_ = resp.Body.Close()
}()
err = json.NewDecoder(resp.Body).Decode(v)
}
return resp, err
}