使用CloudFlare的API自动更新域名DNS解析

CloudFlare的API文档地址

https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

const (
	AuthEmail   = "YOUR_EMAIL"
	AuthKey     = "YOUR_AUTH_KEY"
	ZoneID      = "YOUR_ZONE_ID"
	DNSRecordID = "YOUR_RECORD_ID"
)

func apiRequest(url, data string) ([]byte, error) {

	var request *http.Request
	var err error

	if data == "" {
		request, err = http.NewRequest("GET", url, nil)
	} else {
		request, err = http.NewRequest("PUT", url, strings.NewReader(data))
	}

	if err != nil {
		return nil, err
	}

	request.Header.Add("X-Auth-Email", AuthEmail)
	request.Header.Add("X-Auth-Key", AuthKey)
	request.Header.Add("Content-Type", "application/json")

	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	if response.StatusCode == 200 {
		return body, nil
	} else {
		return nil, errors.New(string(body))
	}

}

func getRecord() string {
	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s", ZoneID, DNSRecordID)
	r, err := apiRequest(url, "")
	if err != nil {
		return err.Error()
	}
	match := regexp.MustCompile(`"content":"([\d\.]+)"`).FindSubmatch(r)
	if len(match) == 2 {
		return string(match[1])
	}
	return "error 00"
}

func updateRecord(ip string) string {
	url := fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s", ZoneID, DNSRecordID)
	r, err := apiRequest(url, fmt.Sprintf(`{"type":"A","name":"share.moguapp.net","content":"%s"}`, ip))
	if err != nil {
		return err.Error()
	}
	if strings.Contains(string(r), `"errors":[]`) {
		return "success"
	}
	return "error 01"
}

func main() {
	u := updateRecord("127.0.0.5")
	fmt.Println(u)
	r := getRecord()
	fmt.Println(r)
}