2024-03-28 12:57:35 -04:00
|
|
|
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)
|
2024-03-28 12:57:35 -04:00
|
|
|
|
|
|
|
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)
|
2024-03-28 12:57:35 -04:00
|
|
|
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)
|
2024-03-28 12:57:35 -04:00
|
|
|
|
|
|
|
req, _ := http.NewRequest("DELETE", url, nil)
|
|
|
|
|
2024-04-03 16:27:55 -04:00
|
|
|
req.Header.Add("Authorization", "Bearer "+adapter.APIToken)
|
2024-03-28 12:57:35 -04:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|