2015-09-07 13:25:13 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"gopkg.in/fsnotify.v1"
|
|
|
|
"github.com/BurntSushi/toml"
|
2015-09-07 15:39:22 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2015-09-07 13:25:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type FileProvider struct {
|
2015-09-07 15:39:22 +00:00
|
|
|
Filename string
|
2015-09-07 13:25:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (provider *FileProvider) Provide(serviceChan chan<- *Service){
|
|
|
|
watcher, err := fsnotify.NewWatcher()
|
|
|
|
if err != nil {
|
2015-09-07 15:39:22 +00:00
|
|
|
log.Println(err)
|
|
|
|
return
|
2015-09-07 13:25:13 +00:00
|
|
|
}
|
|
|
|
defer watcher.Close()
|
|
|
|
|
2015-09-07 15:39:22 +00:00
|
|
|
file, err := os.Open(provider.Filename)
|
2015-09-07 13:25:13 +00:00
|
|
|
if err != nil {
|
2015-09-07 15:39:22 +00:00
|
|
|
log.Println(err)
|
|
|
|
return
|
2015-09-07 13:25:13 +00:00
|
|
|
}
|
2015-09-07 15:39:22 +00:00
|
|
|
defer file.Close()
|
2015-09-07 13:25:13 +00:00
|
|
|
|
|
|
|
done := make(chan bool)
|
|
|
|
// Process events
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case event := <-watcher.Events:
|
2015-09-07 15:39:22 +00:00
|
|
|
if(strings.Contains(event.Name,file.Name())){
|
|
|
|
log.Println("event:", event)
|
|
|
|
service := provider.LoadFileConfig(file.Name())
|
|
|
|
serviceChan <- service
|
|
|
|
}
|
2015-09-07 13:25:13 +00:00
|
|
|
case error := <-watcher.Errors:
|
|
|
|
log.Println("error:", error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2015-09-07 15:39:22 +00:00
|
|
|
err = watcher.Add(filepath.Dir(file.Name()))
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
return
|
|
|
|
}
|
2015-09-07 13:25:13 +00:00
|
|
|
|
2015-09-07 13:25:13 +00:00
|
|
|
|
2015-09-07 15:39:22 +00:00
|
|
|
service:= provider.LoadFileConfig(file.Name())
|
2015-09-07 13:25:13 +00:00
|
|
|
serviceChan <- service
|
|
|
|
<-done
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2015-09-07 15:39:22 +00:00
|
|
|
func (provider *FileProvider) LoadFileConfig(filename string) *Service {
|
2015-09-07 13:25:13 +00:00
|
|
|
service := new(Service)
|
2015-09-07 15:39:22 +00:00
|
|
|
if _, err := toml.DecodeFile(filename, service); err != nil {
|
2015-09-07 13:25:13 +00:00
|
|
|
log.Println("Error reading file:", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return service
|
|
|
|
}
|