hatecomputers.club/adapters/cloudflare/cloudflare.go

77 lines
1.8 KiB
Go
Raw 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)
reqBody := fmt.Sprintf(`{"type":"%s","name":"%s","content":"%s","ttl":%d,"proxied":false}`, record.Type, record.Name, record.Content, record.TTL)
payload := strings.NewReader(reqBody)
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
}
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
}