Push code

This commit is contained in:
2026-01-28 23:03:50 +01:00
parent 5bd203b516
commit 00bbd6534b
19 changed files with 1224 additions and 0 deletions

79
dns/cloudflare.go Normal file
View File

@@ -0,0 +1,79 @@
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
}