traefik/file.go

69 lines
1.2 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 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())){
log.Println("event:", event)
service := provider.LoadFileConfig(file.Name())
serviceChan <- service
}
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 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
}