lego/providers/dns/easydns/client.go

97 lines
2.3 KiB
Go
Raw Normal View History

2019-04-29 00:03:04 +00:00
package easydns
import (
"bytes"
"encoding/json"
"fmt"
2021-08-25 09:44:11 +00:00
"io"
2019-04-29 00:03:04 +00:00
"net/http"
2023-02-09 16:19:58 +00:00
"net/url"
2019-04-29 00:03:04 +00:00
)
const defaultEndpoint = "https://rest.easydns.net"
type zoneRecord struct {
ID string `json:"id,omitempty"`
Domain string `json:"domain"`
Host string `json:"host"`
TTL string `json:"ttl"`
Prio string `json:"prio"`
Type string `json:"type"`
Rdata string `json:"rdata"`
LastMod string `json:"last_mod,omitempty"`
Revoked int `json:"revoked,omitempty"`
NewHost string `json:"new_host,omitempty"`
}
type addRecordResponse struct {
Msg string `json:"msg"`
Tm int `json:"tm"`
Data zoneRecord `json:"data"`
Status int `json:"status"`
}
func (d *DNSProvider) addRecord(domain string, record interface{}) (string, error) {
2023-02-09 16:19:58 +00:00
endpoint := d.config.Endpoint.JoinPath("zones", "records", "add", domain, "TXT")
2019-04-29 00:03:04 +00:00
response := &addRecordResponse{}
2023-02-09 16:19:58 +00:00
err := d.doRequest(http.MethodPut, endpoint, record, response)
2019-04-29 00:03:04 +00:00
if err != nil {
return "", err
}
recordID := response.Data.ID
return recordID, nil
}
func (d *DNSProvider) deleteRecord(domain, recordID string) error {
2023-02-09 16:19:58 +00:00
endpoint := d.config.Endpoint.JoinPath("zones", "records", domain, recordID)
2019-04-29 00:03:04 +00:00
2023-02-09 16:19:58 +00:00
return d.doRequest(http.MethodDelete, endpoint, nil, nil)
2019-04-29 00:03:04 +00:00
}
2023-02-09 16:19:58 +00:00
func (d *DNSProvider) doRequest(method string, endpoint *url.URL, requestMsg, responseMsg interface{}) error {
2019-04-29 00:03:04 +00:00
reqBody := &bytes.Buffer{}
if requestMsg != nil {
err := json.NewEncoder(reqBody).Encode(requestMsg)
if err != nil {
return err
}
}
2023-02-09 16:19:58 +00:00
query := endpoint.Query()
query.Set("format", "json")
endpoint.RawQuery = query.Encode()
2019-04-29 00:03:04 +00:00
request, err := http.NewRequest(method, endpoint.String(), reqBody)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.SetBasicAuth(d.config.Token, d.config.Key)
response, err := d.config.HTTPClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
2021-08-25 09:44:11 +00:00
body, err := io.ReadAll(response.Body)
2019-04-29 00:03:04 +00:00
if err != nil {
2020-02-27 18:14:46 +00:00
return fmt.Errorf("%d: failed to read response body: %w", response.StatusCode, err)
2019-04-29 00:03:04 +00:00
}
return fmt.Errorf("%d: request failed: %v", response.StatusCode, string(body))
}
if responseMsg != nil {
return json.NewDecoder(response.Body).Decode(responseMsg)
}
return nil
}