2023-06-15 22:04:39 -04:00
|
|
|
package conf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2023-09-21 00:34:03 -04:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2023-06-15 22:04:39 -04:00
|
|
|
"time"
|
2024-01-26 11:55:43 -05:00
|
|
|
|
|
|
|
"github.com/fsnotify/fsnotify"
|
2023-06-15 22:04:39 -04:00
|
|
|
)
|
|
|
|
|
2023-09-21 00:34:03 -04:00
|
|
|
func (p *Conf) Watch(filePath, xDnsPath string, sDnsPath string, reload func()) error {
|
2023-06-15 22:04:39 -04:00
|
|
|
watcher, err := fsnotify.NewWatcher()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("new watcher error: %s", err)
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
var pre time.Time
|
|
|
|
defer watcher.Close()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case e := <-watcher.Events:
|
|
|
|
if e.Has(fsnotify.Chmod) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if pre.Add(10 * time.Second).After(time.Now()) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
pre = time.Now()
|
|
|
|
go func() {
|
2023-07-27 13:07:56 -04:00
|
|
|
time.Sleep(5 * time.Second)
|
2023-09-21 00:34:03 -04:00
|
|
|
switch filepath.Base(strings.TrimSuffix(e.Name, "~")) {
|
|
|
|
case filepath.Base(xDnsPath), filepath.Base(sDnsPath):
|
2023-07-19 00:03:09 -04:00
|
|
|
log.Println("DNS file changed, reloading...")
|
2023-09-21 00:34:03 -04:00
|
|
|
default:
|
2024-01-26 11:55:43 -05:00
|
|
|
log.Println("config file changed, reloading...")
|
2023-07-19 00:03:09 -04:00
|
|
|
}
|
2023-06-15 22:04:39 -04:00
|
|
|
*p = *New()
|
|
|
|
err := p.LoadFromPath(filePath)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("reload config error: %s", err)
|
|
|
|
}
|
|
|
|
reload()
|
|
|
|
log.Println("reload config success")
|
|
|
|
}()
|
|
|
|
case err := <-watcher.Errors:
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("File watcher error: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2024-01-26 11:55:43 -05:00
|
|
|
err = watcher.Add(filePath)
|
2023-06-15 22:04:39 -04:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("watch file error: %s", err)
|
|
|
|
}
|
2023-09-21 00:34:03 -04:00
|
|
|
if xDnsPath != "" {
|
2024-01-26 11:55:43 -05:00
|
|
|
err = watcher.Add(xDnsPath)
|
2023-09-21 00:34:03 -04:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("watch dns file error: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if sDnsPath != "" {
|
2024-01-26 11:55:43 -05:00
|
|
|
err = watcher.Add(sDnsPath)
|
2023-07-19 00:03:09 -04:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("watch dns file error: %s", err)
|
|
|
|
}
|
|
|
|
}
|
2023-06-15 22:04:39 -04:00
|
|
|
return nil
|
|
|
|
}
|