traefik/file.go

74 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"log"
"gopkg.in/fsnotify.v1"
"github.com/BurntSushi/toml"
2015-09-07 15:39:22 +00:00
"os"
"path/filepath"
"strings"
)
type FileProvider struct {
2015-09-07 16:10:33 +00:00
Watch bool
2015-09-07 15:39:22 +00:00
Filename string
}
2015-09-07 22:15:14 +00:00
func (provider *FileProvider) Provide(configurationChan chan<- *Configuration){
watcher, err := fsnotify.NewWatcher()
if err != nil {
2015-09-07 15:39:22 +00:00
log.Println(err)
return
}
defer watcher.Close()
2015-09-07 15:39:22 +00:00
file, err := os.Open(provider.Filename)
if err != nil {
2015-09-07 15:39:22 +00:00
log.Println(err)
return
}
2015-09-07 15:39:22 +00:00
defer file.Close()
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())){
2015-09-07 21:25:07 +00:00
log.Println("File event:", event)
2015-09-07 22:15:14 +00:00
configuration := provider.LoadFileConfig(file.Name())
if(configuration != nil) {
configurationChan <- configuration
2015-09-07 21:25:07 +00:00
}
2015-09-07 15:39:22 +00:00
}
case error := <-watcher.Errors:
log.Println("error:", error)
}
}
}()
2015-09-07 16:10:33 +00:00
if(provider.Watch){
err = watcher.Add(filepath.Dir(file.Name()))
}
2015-09-07 15:39:22 +00:00
if err != nil {
log.Println(err)
return
}
2015-09-07 22:15:14 +00:00
configuration := provider.LoadFileConfig(file.Name())
configurationChan <- configuration
<-done
}
2015-09-07 22:15:14 +00:00
func (provider *FileProvider) LoadFileConfig(filename string) *Configuration {
configuration := new(Configuration)
if _, err := toml.DecodeFile(filename, configuration); err != nil {
log.Println("Error reading file:", err)
return nil
}
2015-09-07 22:15:14 +00:00
return configuration
}