fix: cloudflare update performance
This commit is contained in:
@@ -1,15 +1,22 @@
|
||||
package cloudflare
|
||||
|
||||
import (
|
||||
"context"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/cloudflare/cloudflare-go"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/cloudflare/cloudflare-go"
|
||||
)
|
||||
|
||||
type Cloudflare struct {
|
||||
Zone string `json:"zone" yaml:"zone"`
|
||||
Token string `json:"token" yaml:"token"`
|
||||
Zone string `json:"zone" yaml:"zone"`
|
||||
RecordId string `json:"record_id" yaml:"record_id"`
|
||||
Token string `json:"token" yaml:"token"`
|
||||
Email string `json:"email" yaml:"email"`
|
||||
}
|
||||
|
||||
type DnsProvider struct {
|
||||
@@ -37,31 +44,43 @@ func New(ttl int, conf Cloudflare, Http *http.Client) (*DnsProvider, error) {
|
||||
}
|
||||
|
||||
func (a DnsProvider) SetDomainRecord(domain, ip string) error {
|
||||
records, _, err := a.Api.ListDNSRecords(context.Background(), a.ZoneResource, cloudflare.ListDNSRecordsParams{
|
||||
Type: "A",
|
||||
Name: domain,
|
||||
})
|
||||
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s", a.Zone, a.RecordId)
|
||||
proxied := false
|
||||
payload := cloudflare.DNSRecord{
|
||||
Type: "A",
|
||||
Name: domain,
|
||||
Content: ip,
|
||||
TTL: a.TTL,
|
||||
Proxied: &proxied,
|
||||
Comment: "DDNS for " + domain,
|
||||
}
|
||||
|
||||
jsonPayload, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(records) == 0 {
|
||||
_, err = a.Api.CreateDNSRecord(context.Background(), a.ZoneResource, cloudflare.CreateDNSRecordParams{
|
||||
Type: "A",
|
||||
Name: domain,
|
||||
Content: ip,
|
||||
TTL: a.TTL,
|
||||
})
|
||||
return err
|
||||
} else {
|
||||
record := records[0]
|
||||
if record.Content == ip {
|
||||
return nil
|
||||
}
|
||||
_, err = a.Api.UpdateDNSRecord(context.Background(), a.ZoneResource, cloudflare.UpdateDNSRecordParams{
|
||||
ID: record.ID,
|
||||
Content: ip,
|
||||
})
|
||||
// Make the HTTP GET request
|
||||
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonPayload))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("X-Auth-Email", a.Email)
|
||||
req.Header.Set("X-Auth-Key", a.Token)
|
||||
time.Sleep(time.Millisecond * 200) // avoid request too fast after login
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
}
|
||||
fmt.Println(string(body), resp.Status)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user