Skip to content

Commit

Permalink
add config reloader
Browse files Browse the repository at this point in the history
  • Loading branch information
evanzhang87 committed May 1, 2024
1 parent 52734a4 commit 919769b
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 2 deletions.
26 changes: 24 additions & 2 deletions cmd/config/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package main
import (
"fmt"
"github.com/evanzhang87/evans-tools/pkg/config"
"os"
"os/signal"
"time"
)

type Config struct {
Expand All @@ -18,9 +21,28 @@ func (c *Config) print() {

func main() {
var conf Config
err := config.LoadConfig(&conf, "config.yaml")
reloader := config.NewReloader(&conf)
err := reloader.WatchPath("config.yaml")
if err != nil {
fmt.Println(err.Error())
}
conf.print()
signChan := make(chan os.Signal, 1)
signal.Notify(signChan, os.Kill, os.Interrupt)
configChan := reloader.SubscribeConfig()
reloadTicker := time.NewTicker(time.Second * 10)
for {
select {
case <-signChan:
return
case configOutlet := <-configChan:
if configOutlet != nil {
configOutlet.(*Config).print()
}
case <-reloadTicker.C:
confFetch := reloader.FetchConfig()
if confFetch != nil {
confFetch.(*Config).print()
}
}
}
}
73 changes: 73 additions & 0 deletions pkg/config/reloader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package config

import (
"github.com/fsnotify/fsnotify"
"sync"
)

type Reloader struct {
configInstance interface{}
mutex *sync.Mutex

watcher *fsnotify.Watcher
opList []fsnotify.Op

outlet chan interface{}
}

func NewReloader(config interface{}) *Reloader {
return &Reloader{
configInstance: config,
mutex: &sync.Mutex{},

opList: []fsnotify.Op{fsnotify.Write, fsnotify.Create},
}
}

func (r *Reloader) WithOps(ops ...fsnotify.Op) {
r.opList = ops
}

func (r *Reloader) WatchPath(path string) error {
var err error
r.watcher, err = fsnotify.NewWatcher()
if err != nil {
return err
}
err = r.watcher.Add(path)
if err != nil {
return err
}
go func() {
for event := range r.watcher.Events {
for _, op := range r.opList {
if event.Op == op {
r.mutex.Lock()
_ = LoadConfig(r.configInstance, path)
if r.outlet != nil {
r.outlet <- r.configInstance
}
r.mutex.Unlock()
}
}
}
}()
return err
}

func (r *Reloader) FetchConfig() interface{} {
if r.mutex != nil {
r.mutex.Lock()
defer r.mutex.Unlock()
}
return r.configInstance
}

func (r *Reloader) SubscribeConfig() chan interface{} {
r.outlet = make(chan interface{}, 1)
return r.outlet
}

func (r *Reloader) Stop() {
_ = r.watcher.Close()
}

0 comments on commit 919769b

Please sign in to comment.