lego/providers/dns/sonic/internal/client.go

97 lines
2.1 KiB
Go
Raw Normal View History

2021-04-25 09:37:35 +00:00
package internal
import (
"bytes"
2023-05-05 07:49:38 +00:00
"context"
2021-04-25 09:37:35 +00:00
"encoding/json"
"errors"
"fmt"
2021-08-25 09:44:11 +00:00
"io"
2021-04-25 09:37:35 +00:00
"net/http"
2023-05-05 07:49:38 +00:00
"net/url"
2021-04-25 09:37:35 +00:00
"time"
2023-05-05 07:49:38 +00:00
"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
2021-04-25 09:37:35 +00:00
)
const baseURL = "https://public-api.sonic.net/dyndns"
// Client Sonic client.
type Client struct {
2023-05-05 07:49:38 +00:00
userID string
apiKey string
2021-04-25 09:37:35 +00:00
baseURL string
HTTPClient *http.Client
}
// NewClient creates a Client.
func NewClient(userID, apiKey string) (*Client, error) {
if userID == "" || apiKey == "" {
return nil, errors.New("credentials are missing")
}
return &Client{
userID: userID,
apiKey: apiKey,
baseURL: baseURL,
HTTPClient: &http.Client{Timeout: 10 * time.Second},
}, nil
}
// SetRecord creates or updates a TXT records.
// Sonic does not provide a delete record API endpoint.
// https://public-api.sonic.net/dyndns#updating_or_adding_host_records
2023-05-05 07:49:38 +00:00
func (c *Client) SetRecord(ctx context.Context, hostname string, value string, ttl int) error {
2021-04-25 09:37:35 +00:00
payload := &Record{
UserID: c.userID,
APIKey: c.apiKey,
Hostname: hostname,
Value: value,
TTL: ttl,
Type: "TXT",
}
body, err := json.Marshal(payload)
if err != nil {
2023-05-05 07:49:38 +00:00
return fmt.Errorf("failed to create request JSON body: %w", err)
2021-04-25 09:37:35 +00:00
}
2023-05-05 07:49:38 +00:00
endpoint, err := url.JoinPath(c.baseURL, "host")
2021-04-25 09:37:35 +00:00
if err != nil {
return err
}
2023-05-05 07:49:38 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodPut, endpoint, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("unable to create request: %w", err)
}
req.Header.Set("Accept", "application/json")
2021-04-25 09:37:35 +00:00
req.Header.Set("content-type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
2023-05-05 07:49:38 +00:00
return errutils.NewHTTPDoError(req, err)
2021-04-25 09:37:35 +00:00
}
defer func() { _ = resp.Body.Close() }()
2021-08-25 09:44:11 +00:00
raw, err := io.ReadAll(resp.Body)
2021-04-25 09:37:35 +00:00
if err != nil {
2023-05-05 07:49:38 +00:00
return errutils.NewReadResponseError(req, resp.StatusCode, err)
2021-04-25 09:37:35 +00:00
}
r := APIResponse{}
err = json.Unmarshal(raw, &r)
if err != nil {
2023-05-05 07:49:38 +00:00
return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
2021-04-25 09:37:35 +00:00
}
if r.Result != 200 {
return fmt.Errorf("API response code: %d, %s", r.Result, r.Message)
}
return nil
}