cloudflare-ddns/main.go

79 lines
1.6 KiB
Go
Raw Normal View History

2022-08-17 09:58:45 -07:00
package main
import (
"errors"
"io"
"log"
"net/http"
"time"
)
var (
2023-05-28 15:37:38 -07:00
ErrInvalidStatusCode error = errors.New("did not get an acceptiable status code from the server")
2022-08-17 09:58:45 -07:00
ErrFailedToDecodeBody error = errors.New("unable to decode the body")
ErrFailedToDecodeJson error = errors.New("unexpected json format was returned")
2023-05-28 15:37:38 -07:00
ErrWasNotJson error = errors.New("response from server was not json")
ErrDomainNotFound error = errors.New("unable to find requested domain on cloudflare")
2022-08-17 09:58:45 -07:00
)
func GetCurrentIpAddress() (string, error) {
resp, err := http.Get("https://v4.ident.me")
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", ErrInvalidStatusCode
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", ErrFailedToDecodeBody
}
return string(body), nil
}
func main() {
config := NewConfigClient()
2023-05-28 15:37:38 -07:00
cfg := config.LoadConfig()
if cfg.Email == "" {
2022-08-17 09:58:45 -07:00
log.Println("Unable to find 'EMAIL' env value.")
return
}
2023-05-28 15:37:38 -07:00
if cfg.Token == "" {
2022-08-17 09:58:45 -07:00
log.Println("Unable to find 'API_TOKEN' env value.")
2023-05-28 15:37:38 -07:00
return
2022-08-17 09:58:45 -07:00
}
2023-05-28 15:37:38 -07:00
if cfg.Domain == "" {
2022-08-17 09:58:45 -07:00
log.Println("Unable to find 'DOMAIN' env value.")
2023-05-28 15:37:38 -07:00
return
2022-08-17 09:58:45 -07:00
}
2023-05-28 15:37:38 -07:00
if len(cfg.Hosts) == 0 {
2022-08-17 09:58:45 -07:00
log.Println("Unable to find 'HOSTS' env value.")
}
2023-05-28 15:37:38 -07:00
log.Println("Config Check: OK")
2022-08-17 09:58:45 -07:00
cron := NewCron()
log.Println("Cloudflare Check will run every 15 minutes.")
2023-05-28 15:37:38 -07:00
cron.scheduler.AddFunc("0/5 * * * *", func() {
cron.RunCloudflareCheck(cfg.Token, cfg.Email, cfg.Domain, cfg.Hosts)
})
cron.scheduler.AddFunc("0/1 * * * *", func() {
cron.HelloWorldJob()
2022-08-17 09:58:45 -07:00
})
cron.scheduler.Start()
log.Println("Application has started!")
for {
time.Sleep(30 * time.Second)
}
}