forked from go-acme/lego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
110 lines (86 loc) · 2.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
package internal
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)
const (
defaultBaseURL = "https://api.dns.constellix.com"
defaultVersion = "v1"
)
// Client the Constellix client.
type Client struct {
BaseURL string
HTTPClient *http.Client
common service // Reuse a single struct instead of allocating one for each service on the heap.
// Services used for communicating with the API
Domains *DomainService
TxtRecords *TxtRecordService
}
// NewClient Creates a Constellix client.
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = &http.Client{Timeout: 5 * time.Second}
}
client := &Client{
BaseURL: defaultBaseURL,
HTTPClient: httpClient,
}
client.common.client = client
client.Domains = (*DomainService)(&client.common)
client.TxtRecords = (*TxtRecordService)(&client.common)
return client
}
type service struct {
client *Client
}
// do sends an API request and returns the API response.
func (c *Client) do(req *http.Request, result any) error {
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
err = checkResponse(resp)
if err != nil {
return err
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return errutils.NewReadResponseError(req, resp.StatusCode, err)
}
if err = json.Unmarshal(raw, result); err != nil {
return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}
return nil
}
func (c *Client) createEndpoint(fragment ...string) (string, error) {
return url.JoinPath(c.BaseURL, fragment...)
}
func checkResponse(resp *http.Response) error {
if resp.StatusCode == http.StatusOK {
return nil
}
raw, err := io.ReadAll(resp.Body)
if err == nil && raw != nil {
errAPI := &APIError{StatusCode: resp.StatusCode}
if json.Unmarshal(raw, errAPI) != nil {
return fmt.Errorf("API error: status code: %d: %v", resp.StatusCode, string(raw))
}
switch resp.StatusCode {
case http.StatusNotFound:
return &NotFound{APIError: errAPI}
case http.StatusBadRequest:
return &BadRequest{APIError: errAPI}
default:
return errAPI
}
}
return fmt.Errorf("API error, status code: %d", resp.StatusCode)
}