From 6d95a6639f0156a864258e9fe8185ec0215b1996 Mon Sep 17 00:00:00 2001 From: Awstin Date: Tue, 19 Nov 2024 19:42:05 -0500 Subject: [PATCH] Dynamic DNS update script --- ddns.go | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 ddns.go diff --git a/ddns.go b/ddns.go new file mode 100644 index 0000000..0093ec7 --- /dev/null +++ b/ddns.go @@ -0,0 +1,80 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "strings" +) + +const ( + updateUrl = "https://api.porkbun.com/api/json/v3/dns/editByNameType/awstinchubb.com/A" + getUrl = "https://api.porkbun.com/api/json/v3/dns/retrieveByNameType/awstinchubb.com/A" + apiKey = "DDNS_API_KEY" + secretKey = "DDNS_SECRET_KEY" +) + +type Record struct { + Id string + Name string + Type string + Content string + Ttl string + Prio string + Notes string +} + +type ResponseBody struct { + Status string + Cloudflare string + Records []Record +} + +func main() { + ip := getIp() + record := getRecord() + + if ip != record.Content { + updateRecord(ip) + } +} + +func getRecord() Record { + body := strings.NewReader(fmt.Sprintf("{\"secretapikey\": \"%s\", \"apikey\": \"%s\"}", os.Getenv(secretKey), os.Getenv(apiKey))) + + resp, err := http.Post(getUrl, "application/json", body) + if err != nil { + log.Fatal(err) + } + defer resp.Body.Close() + + resBodyBites, err := io.ReadAll(resp.Body) + var resBody ResponseBody + json.Unmarshal(resBodyBites, &resBody) + return resBody.Records[0] +} + +func updateRecord(ipAddr string) { + body := strings.NewReader(fmt.Sprintf("{\"secretapikey\": \"%s\", \"apikey\": \"%s\", \"content\": \"%s\", \"ttl\": \"600\"}", os.Getenv(secretKey), os.Getenv(apiKey), ipAddr)) + fmt.Println(body) + + resp, err := http.Post(updateUrl, "application/json", body) + if err != nil { + log.Fatal(err) + } + defer resp.Body.Close() +} + +func getIp() string { + resp, err := http.Get("https://icanhazip.com") + + if err != nil { + log.Fatal(err) + } + defer resp.Body.Close() + resBodyBites, err := io.ReadAll(resp.Body) + return strings.TrimSpace(string(resBodyBites)) +}