Compare commits

..

2 Commits

5 changed files with 130 additions and 33 deletions

View File

@ -1,15 +1,14 @@
APP_NAME = DDNSUpdater APP_NAME = DDNSUpdater
BIN_DIR = bin BIN_DIR = bin
VERSION = 0.1.0 VERSION = 0.1.0
OUT = $(BIN_DIR)\$(APP_NAME).exe
FLAGS = -trimpath -ldflags="-s -w -X main.version=$(VERSION)"
all: build run all: build run
# Default build
build: build:
@if not exist $(BIN_DIR) mkdir $(BIN_DIR) @if not exist $(BIN_DIR) mkdir $(BIN_DIR)
set CGO_ENABLED=0 && \ cmd /c "set CGO_ENABLED=0 && go build $(FLAGS) -o $(OUT) ."
set GOOS=windows && set GOARCH=amd64 && \
go build -ldflags="-s -w -trimpath -X main.version=$(VERSION)" -o $(BIN_DIR)\$(APP_NAME).exe .
run: run:
go run . go run .
@ -17,13 +16,6 @@ run:
clean: clean:
@if exist $(BIN_DIR) rmdir /s /q $(BIN_DIR) @if exist $(BIN_DIR) rmdir /s /q $(BIN_DIR)
# Windows-specific optimized build
windows:
@if not exist $(BIN_DIR) mkdir $(BIN_DIR)
set CGO_ENABLED=0 && \
set GOOS=windows && set GOARCH=amd64 && \
go build -ldflags="-s -w -trimpath -X main.version=$(VERSION)" -o $(BIN_DIR)\$(APP_NAME).exe .
tidy: tidy:
go mod tidy go mod tidy

Binary file not shown.

4
go.mod
View File

@ -1,3 +1,7 @@
module triztech/hamza-zakaria/DDNSUpdater module triztech/hamza-zakaria/DDNSUpdater
go 1.25.5 go 1.25.5
require github.com/fsnotify/fsnotify v1.9.0
require golang.org/x/sys v0.13.0 // indirect

4
go.sum Normal file
View File

@ -0,0 +1,4 @@
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

137
main.go
View File

@ -7,13 +7,16 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"sync"
"time" "time"
"github.com/fsnotify/fsnotify"
) )
type Config struct { type Config struct {
UpdateURL string `json:"update_url"` UpdateURL string `json:"update_url"`
CheckIntervalSecs int `json:"check_interval_seconds"` CheckIntervalSecs int `json:"check_interval_seconds"`
IPCheckURL string `json:"ip_check_url"` IPCheckURL string `json:"ip_check_url"`
} }
func loadConfig(path string) (*Config, error) { func loadConfig(path string) (*Config, error) {
@ -22,25 +25,103 @@ func loadConfig(path string) (*Config, error) {
return nil, err return nil, err
} }
var cfg Config var cfg Config
err = json.Unmarshal(data, &cfg) if err := json.Unmarshal(data, &cfg); err != nil {
if err != nil {
return nil, err return nil, err
} }
return &cfg, nil return &cfg, nil
} }
type configHolder struct {
mu sync.RWMutex
cfg *Config
}
func (h *configHolder) get() *Config {
h.mu.RLock()
defer h.mu.RUnlock()
return h.cfg
}
func (h *configHolder) set(cfg *Config) {
h.mu.Lock()
defer h.mu.Unlock()
h.cfg = cfg
}
func watchConfig(path string, holder *configHolder, tickerReset chan<- time.Duration) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Config watcher: failed to create watcher:", err)
return
}
defer watcher.Close()
if err := watcher.Add(path); err != nil {
fmt.Println("Config watcher: failed to watch file:", err)
return
}
// Debounce timer — editors often fire multiple events per save
// (truncate then write, or swapping a temp file in).
const debounce = 100 * time.Millisecond
var debounceTimer *time.Timer
reload := func() {
newCfg, err := loadConfig(path)
if err != nil {
fmt.Println("Config watcher: failed to reload config:", err)
return
}
oldCfg := holder.get()
holder.set(newCfg)
fmt.Println(time.Now(), "Config reloaded")
if newCfg.CheckIntervalSecs != oldCfg.CheckIntervalSecs {
fmt.Printf("%v Check interval changed: %ds → %ds\n",
time.Now(), oldCfg.CheckIntervalSecs, newCfg.CheckIntervalSecs)
tickerReset <- time.Duration(newCfg.CheckIntervalSecs) * time.Second
}
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
// Write and Create cover both in-place saves and atomic
// rename-based saves (used by vim, many editors on Linux).
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) {
// If it was an atomic rename the old watch target is gone;
// re-add the new file under the same path.
if event.Has(fsnotify.Create) {
_ = watcher.Add(path)
}
if debounceTimer != nil {
debounceTimer.Stop()
}
debounceTimer = time.AfterFunc(debounce, reload)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("Config watcher: error:", err)
}
}
}
func getPublicIP(ipURL string) (string, error) { func getPublicIP(ipURL string) (string, error) {
resp, err := http.Get(ipURL) resp, err := http.Get(ipURL)
if err != nil { if err != nil {
return "", err return "", err
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", err return "", err
} }
return strings.TrimSpace(string(body)), nil return strings.TrimSpace(string(body)), nil
} }
@ -50,7 +131,6 @@ func updateDDNS(url string) error {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed, status code %d", resp.StatusCode) return fmt.Errorf("failed, status code %d", resp.StatusCode)
} }
@ -58,16 +138,23 @@ func updateDDNS(url string) error {
} }
func main() { func main() {
cfg, err := loadConfig("config.json") print("Trying out some prints to see what's going on\n");
const configPath = "config.json"
cfg, err := loadConfig(configPath)
if err != nil { if err != nil {
fmt.Println("Failed to load config:", err) fmt.Println("Failed to load config:", err)
os.Exit(1) os.Exit(1)
} }
//var lastIP string holder := &configHolder{cfg: cfg}
tickerReset := make(chan time.Duration, 1)
go watchConfig(configPath, holder, tickerReset)
lastIP, err := getPublicIP(cfg.IPCheckURL) lastIP, err := getPublicIP(cfg.IPCheckURL)
if err != nil { if err != nil {
fmt.Println("Error getting intial public IP:", err) fmt.Println("Error getting initial public IP:", err)
lastIP = "" lastIP = ""
} else { } else {
fmt.Println(time.Now(), "Starting with current IP:", lastIP) fmt.Println(time.Now(), "Starting with current IP:", lastIP)
@ -77,21 +164,31 @@ func main() {
defer ticker.Stop() defer ticker.Stop()
for { for {
ip, err := getPublicIP(cfg.IPCheckURL) select {
if err != nil { case newInterval := <-tickerReset:
fmt.Println("Error getting public IP:", err) ticker.Reset(newInterval)
} else if ip != lastIP { continue
case <-ticker.C:
current := holder.get()
ip, err := getPublicIP(current.IPCheckURL)
if err != nil {
fmt.Println("Error getting public IP:", err)
continue
}
if ip == lastIP {
fmt.Println(time.Now(), "IP unchanged:", ip)
continue
}
fmt.Println(time.Now(), "IP changed to", ip) fmt.Println(time.Now(), "IP changed to", ip)
if err := updateDDNS(cfg.UpdateURL); err != nil { if err := updateDDNS(current.UpdateURL); err != nil {
fmt.Println("Failed to update DDNS:", err) fmt.Println("Failed to update DDNS:", err)
} else { } else {
fmt.Println(time.Now(), "DDNS updated successfully") fmt.Println(time.Now(), "DDNS updated successfully")
lastIP = ip lastIP = ip
} }
} else {
fmt.Println(time.Now(), "IP unchanged:", ip)
} }
<-ticker.C
} }
} }