hatecomputers.club/adapters/external_dns/cloudflare/cloudflare.go

98 lines
2.5 KiB
Go
Raw Permalink Normal View History

package cloudflare
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
)
type CloudflareDNSResponse struct {
Result database.DNSRecord `json:"result"`
}
2024-04-03 16:27:55 -04:00
type CloudflareExternalDNSAdapter struct {
ZoneId string
APIToken string
}
func (adapter *CloudflareExternalDNSAdapter) CreateDNSRecord(record *database.DNSRecord) (string, error) {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records", adapter.ZoneId)
payload := strings.NewReader(encodeDNSRecord(record))
req, _ := http.NewRequest("POST", url, payload)
2024-04-03 16:27:55 -04:00
req.Header.Add("Authorization", "Bearer "+adapter.APIToken)
req.Header.Add("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
return "", fmt.Errorf("error creating dns record: %s", body)
}
var response CloudflareDNSResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
result := &response.Result
return result.ID, nil
}
func (adapter *CloudflareExternalDNSAdapter) UpdateDNSRecord(record *database.DNSRecord) error {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s", adapter.ZoneId, record.ID)
payload := strings.NewReader(encodeDNSRecord(record))
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Authorization", "Bearer "+adapter.APIToken)
req.Header.Add("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
return fmt.Errorf("error updating dns record: %s", body)
}
return nil
}
2024-04-03 16:27:55 -04:00
func (adapter *CloudflareExternalDNSAdapter) DeleteDNSRecord(id string) error {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s", adapter.ZoneId, id)
req, _ := http.NewRequest("DELETE", url, nil)
2024-04-03 16:27:55 -04:00
req.Header.Add("Authorization", "Bearer "+adapter.APIToken)
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
return fmt.Errorf("error deleting dns record: %s", body)
}
return nil
}
func encodeDNSRecord(record *database.DNSRecord) string {
return fmt.Sprintf(`{"type":"%s","name":"%s","content":"%s","ttl":%d,"proxied":false}`, record.Type, record.Name, record.Content, record.TTL)
}