config.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "time"
  7. "code.google.com/p/gcfg"
  8. "github.com/howeyc/fsnotify"
  9. )
  10. type AppConfig struct {
  11. StatHat struct {
  12. ApiKey string
  13. }
  14. InfluxDB struct {
  15. Host string
  16. Database string
  17. Username string
  18. Password string
  19. }
  20. Flags struct {
  21. HasStatHat bool
  22. }
  23. GeoIP struct {
  24. Directory string
  25. }
  26. }
  27. var Config = new(AppConfig)
  28. func configWatcher(fileName string) {
  29. configReader(fileName)
  30. watcher, err := fsnotify.NewWatcher()
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. if err := watcher.Watch(*flagconfig); err != nil {
  36. fmt.Println(err)
  37. return
  38. }
  39. for {
  40. select {
  41. case ev := <-watcher.Event:
  42. if ev.Name == fileName {
  43. if ev.IsCreate() || ev.IsModify() || ev.IsRename() {
  44. time.Sleep(200 * time.Millisecond)
  45. configReader(fileName)
  46. }
  47. }
  48. case err := <-watcher.Error:
  49. log.Println("fsnotify error:", err)
  50. }
  51. }
  52. }
  53. var lastReadConfig time.Time
  54. func configReader(fileName string) error {
  55. stat, err := os.Stat(fileName)
  56. if err != nil {
  57. log.Printf("Failed to find config file: %s\n", err)
  58. return err
  59. }
  60. if !stat.ModTime().After(lastReadConfig) {
  61. return err
  62. }
  63. lastReadConfig = time.Now()
  64. log.Printf("Loading config: %s\n", fileName)
  65. cfg := new(AppConfig)
  66. err = gcfg.ReadFileInto(cfg, fileName)
  67. if err != nil {
  68. log.Printf("Failed to parse config data: %s\n", err)
  69. return err
  70. }
  71. cfg.Flags.HasStatHat = len(cfg.StatHat.ApiKey) > 0
  72. // log.Println("STATHAT APIKEY:", cfg.StatHat.ApiKey)
  73. // log.Println("STATHAT FLAG :", cfg.Flags.HasStatHat)
  74. Config = cfg
  75. return nil
  76. }