Dynamic DNS update script
This commit is contained in:
parent
670b757c34
commit
6d95a6639f
1 changed files with 80 additions and 0 deletions
80
ddns.go
Normal file
80
ddns.go
Normal file
|
|
@ -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))
|
||||
}
|
||||
Loading…
Reference in a new issue