traefik/file.go

74 lines
1.3 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
}
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
}
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 15:39:22 +00:00
service := provider.LoadFileConfig(file.Name())
2015-09-07 21:25:07 +00:00
if(service != nil) {
serviceChan <- service
}
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 15:39:22 +00:00
service:= provider.LoadFileConfig(file.Name())
serviceChan <- service
<-done
}
2015-09-07 15:39:22 +00:00
func (provider *FileProvider) LoadFileConfig(filename string) *Service {
service := new(Service)
2015-09-07 15:39:22 +00:00
if _, err := toml.DecodeFile(filename, service); err != nil {
log.Println("Error reading file:", err)
return nil
}
return service
}