ddns_updater/ddns.go

80 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-11-19 19:42:05 -05:00
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))
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))
}