traefik/file.go

71 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
2015-09-07 15:39:22 +00:00
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"gopkg.in/fsnotify.v1"
)
type FileProvider struct {
2015-09-12 13:10:03 +00:00
Watch bool
2015-09-07 15:39:22 +00:00
Filename string
}
func (provider *FileProvider) Provide(configurationChan chan<- configMessage) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
2015-09-11 14:37:13 +00:00
log.Error("Error creating file watcher", err)
return err
}
2015-09-07 15:39:22 +00:00
file, err := os.Open(provider.Filename)
if err != nil {
2015-09-11 14:37:13 +00:00
log.Error("Error opening file", err)
return err
}
2015-09-07 15:39:22 +00:00
defer file.Close()
2015-10-03 14:50:53 +00:00
if provider.Watch {
// Process events
go func() {
defer watcher.Close()
for {
select {
case event := <-watcher.Events:
if strings.Contains(event.Name, file.Name()) {
log.Debug("File event:", event)
configuration := provider.LoadFileConfig(file.Name())
if configuration != nil {
configurationChan <- configMessage{"file", configuration}
}
2015-09-07 21:25:07 +00:00
}
2015-10-03 14:50:53 +00:00
case error := <-watcher.Errors:
log.Error("Watcher event error", error)
2015-09-07 15:39:22 +00:00
}
}
2015-10-03 14:50:53 +00:00
}()
2015-09-07 16:10:33 +00:00
err = watcher.Add(filepath.Dir(file.Name()))
2015-10-03 14:50:53 +00:00
if err != nil {
log.Error("Error adding file watcher", err)
return err
}
2015-09-07 15:39:22 +00:00
}
2015-09-07 22:15:14 +00:00
configuration := provider.LoadFileConfig(file.Name())
configurationChan <- configMessage{"file", configuration}
return nil
}
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 {
2015-09-11 14:37:13 +00:00
log.Error("Error reading file:", err)
return nil
}
2015-09-07 22:15:14 +00:00
return configuration
2015-09-12 13:10:03 +00:00
}