dnsupdater/internal/dns/gandi/dnsmanager.go

66 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-10-26 13:01:37 +00:00
package gandi
import (
"fmt"
"net/http"
"github.com/dghubble/sling"
"github.com/pkg/errors"
)
const (
ApiUrl = "https://dns.api.gandi.net/api/v5/"
ARecordUrl = "domains/%s/records/@/A"
)
type DnsManager struct {
sling *sling.Sling
}
func NewDnsManager(client *http.Client, apiKey string) *DnsManager {
return &DnsManager{
sling: sling.New().
Client(client).
Base(ApiUrl).
Set("X-Api-Key", apiKey),
}
}
func (d DnsManager) GetARecord(domainname string) (string, error) {
var response DnsResponse
resp, err := d.sling.New().
Get(fmt.Sprintf(ARecordUrl, domainname)).
ReceiveSuccess(&response)
if err != nil {
return "", errors.Wrap(err, "executing request")
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", errors.Errorf("no 2xx http status code : %d - %s", resp.StatusCode, resp.Status)
}
if len(response.Values) == 0 {
return "", errors.Errorf("no values in response")
}
return response.Values[0], nil
}
func (d DnsManager) SetARecord(domainname string, ip string) error {
resp, err := d.sling.New().
Put(fmt.Sprintf(ARecordUrl, domainname)).
BodyJSON(struct {
TTL int `json:"rrset_ttl"`
Values []string `json:"rrset_values"`
}{
TTL: 600,
Values: []string{ip},
}).ReceiveSuccess(nil)
if err != nil {
return errors.Wrap(err, "executing request")
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return errors.Errorf("no 2xx http status code : %d - %s", resp.StatusCode, resp.Status)
}
return nil
}