80 lines
2.0 KiB
Go
80 lines
2.0 KiB
Go
package dns
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/cloudflare/cloudflare-go/v3"
|
|
"github.com/cloudflare/cloudflare-go/v3/dns"
|
|
"github.com/cloudflare/cloudflare-go/v3/option"
|
|
)
|
|
|
|
var cfClient *cloudflare.Client
|
|
var ctx = context.Background()
|
|
|
|
func UpdateCloudflare(apiToken string, zoneId string, fqdn string, newIP string) error {
|
|
cfClient = cloudflare.NewClient(option.WithAPIToken(apiToken))
|
|
listResp, err := listAllCloudflareRecords(zoneId, fqdn)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = updateCloudflareRecord(apiToken, listResp, zoneId, newIP)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func updateCloudflareRecord(apiToken string, record dns.RecordListResponse, zoneId string, newIP string) (string, error) {
|
|
url := "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records/" + record.ID
|
|
jsonData := []byte(`{"content":"` + newIP + `"}`)
|
|
body := bytes.NewReader(jsonData)
|
|
req, err := http.NewRequest("PATCH", url, body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+apiToken)
|
|
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
fmt.Printf("Status Code: %d\n", resp.StatusCode)
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "", nil
|
|
}
|
|
|
|
respString := string(responseBody)
|
|
|
|
fmt.Printf("Response Body: %s\n", respString)
|
|
return respString, nil
|
|
}
|
|
|
|
func listAllCloudflareRecords(zoneId string, fqdn string) (dns.RecordListResponse, error) {
|
|
records, err := cfClient.DNS.Records.List(
|
|
ctx,
|
|
dns.RecordListParams{
|
|
ZoneID: cloudflare.F(zoneId),
|
|
Name: cloudflare.F(fqdn),
|
|
Type: cloudflare.F(dns.RecordListParamsTypeA),
|
|
})
|
|
if err != nil {
|
|
return dns.RecordListResponse{}, err
|
|
}
|
|
if len(records.Result) == 0 {
|
|
return dns.RecordListResponse{}, fmt.Errorf("no a record found for %s", fqdn)
|
|
}
|
|
|
|
record := records.Result[0]
|
|
|
|
return record, nil
|
|
}
|