-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
52734a4
commit 919769b
Showing
2 changed files
with
97 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |