-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
82 lines (67 loc) · 1.79 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
// Package svc Client for the SVC API.
// https://joker.com/faq/content/6/496/en/let_s-encrypt-support.html
package svc
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/entrustcorporation/dv/providers/internal/errutils"
querystring "github.com/google/go-querystring/query"
)
const defaultBaseURL = "https://svc.joker.com/nic/replace"
type request struct {
Username string `url:"username"`
Password string `url:"password"`
Zone string `url:"zone"`
Label string `url:"label"`
Type string `url:"type"`
Value string `url:"value"`
}
type Client struct {
username string
password string
BaseURL string
HTTPClient *http.Client
}
func NewClient(username, password string) *Client {
return &Client{
username: username,
password: password,
BaseURL: defaultBaseURL,
HTTPClient: &http.Client{Timeout: 5 * time.Second},
}
}
func (c *Client) SendRequest(ctx context.Context, zone, label, value string) error {
payload := request{
Username: c.username,
Password: c.password,
Zone: zone,
Label: label,
Type: "TXT",
Value: value,
}
v, err := querystring.Values(payload)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL, strings.NewReader(v.Encode()))
if err != nil {
return fmt.Errorf("unable to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return errutils.NewReadResponseError(req, resp.StatusCode, err)
}
if resp.StatusCode == http.StatusOK && strings.HasPrefix(string(raw), "OK") {
return nil
}
return fmt.Errorf("error: %d: %s", resp.StatusCode, string(raw))
}