Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config file monitoring feature #73

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
71 changes: 71 additions & 0 deletions configor.go
Expand Up @@ -3,9 +3,13 @@ package configor
import (
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"sync"
"time"

"github.com/fsnotify/fsnotify"
)

type Configor struct {
Expand All @@ -27,6 +31,8 @@ type Config struct {
// go 1.10 or later.
// This field will be ignored when compiled with go versions lower than 1.10.
ErrorOnUnmatchedKeys bool

OnConfigChange func(e fsnotify.Event)
}

// New initialize a Configor
Expand Down Expand Up @@ -119,3 +125,68 @@ func ENV() string {
func Load(config interface{}, files ...string) error {
return New(nil).Load(config, files...)
}

func Watch(config interface{}, files ...string) {
New(nil).Watch(config, files...)
}

func (configor *Configor) Watch(config interface{}, files ...string) {
initWG := sync.WaitGroup{}
initWG.Add(1)
for _, file := range files {

go func() {
watcher, err := newWatcher()
if err != nil {
fmt.Printf("Failed to create watcher for %v, got error %v\n", file, err)
}
defer watcher.Close()

configFile := filepath.Clean(file)
configDir, _ := filepath.Split(configFile)
realConfigFile, _ := filepath.EvalSymlinks(file)

eventsWG := sync.WaitGroup{}
eventsWG.Add(1)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
eventsWG.Done()
return
}

currentConfigFile, _ := filepath.EvalSymlinks(file)
const writeOrCreateMask = fsnotify.Write | fsnotify.Create
if (event.Op&writeOrCreateMask != 0 && currentConfigFile == event.Name) ||
(currentConfigFile != "" && currentConfigFile != realConfigFile) {
err := configor.Load(config, files...)
if err != nil {
fmt.Printf("Failed to reload configuration from %v, got error %v\n", files, err)
}
if configor.Config.OnConfigChange != nil {
configor.Config.OnConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile &&
event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
eventsWG.Done()
return
}

case err, ok := <-watcher.Errors:
if ok {
fmt.Printf("Failed to watch configuration from %v, got error %v\n", files, err)
}
eventsWG.Done()
return
}
}
}()
watcher.Add(configDir)
initWG.Done()
eventsWG.Wait()
}()
initWG.Wait()
}
}
38 changes: 38 additions & 0 deletions configor_test.go
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"reflect"
"testing"
"time"

"github.com/BurntSushi/toml"
"gopkg.in/yaml.v2"
Expand Down Expand Up @@ -681,3 +682,40 @@ func TestLoadNestedConfig(t *testing.T) {
adminConfig := MenuList{}
New(&Config{Verbose: true}).Load(&adminConfig, "admin.yml")
}

func TestWatchNormalConfig(t *testing.T) {
var result testConfig
config := generateDefaultConfig()
if bytes, err := json.Marshal(config); err == nil {
if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
defer file.Close()
defer os.Remove(file.Name())
file.Write(bytes)

//Load(&result, file.Name())
Watch(&result, file.Name())

time.Sleep(time.Second)
if !reflect.DeepEqual(result, config) {
t.Errorf("result should equal to original configuration")
}

config.Hosts = []string{
"whocallthefleet.org",
"abandonship.org",
}
if bytes, err = json.Marshal(config); err != nil {
t.Errorf("Failed to marshal config")
}
file.Seek(0, 0)
file.Write(bytes)

time.Sleep(1 * time.Second)
if !reflect.DeepEqual(result, config) {
t.Errorf("watch test failed: result should equal to original configuration")
}
} else {
t.Errorf("Failed to marshal config")
}
}
}
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -4,5 +4,6 @@ go 1.12

require (
github.com/BurntSushi/toml v0.3.1
github.com/fsnotify/fsnotify v1.5.1
gopkg.in/yaml.v2 v2.2.2
)
4 changes: 4 additions & 0 deletions go.sum
@@ -1,5 +1,9 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=
github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
Expand Down
9 changes: 9 additions & 0 deletions watch.go
@@ -0,0 +1,9 @@
package configor

import "github.com/fsnotify/fsnotify"

type watcher = fsnotify.Watcher

func newWatcher() (*watcher, error) {
return fsnotify.NewWatcher()
}