hosts.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "encoding/json"
  4. "os"
  5. "sync"
  6. )
  7. import (
  8. "github.com/fatih/color"
  9. "github.com/fsnotify/fsnotify"
  10. )
  11. var (
  12. HOSTS = make(map[string][]string)
  13. LOCKER = new(sync.Mutex)
  14. )
  15. // Load the hosts file into memory
  16. func InitHostsList() error {
  17. LOCKER.Lock()
  18. defer LOCKER.Unlock()
  19. f, e := os.OpenFile(*HOSTS_FILE, os.O_RDONLY|os.O_CREATE, 0666)
  20. if e != nil {
  21. return e
  22. }
  23. defer f.Close()
  24. finfo, err := f.Stat()
  25. if err != nil {
  26. return err
  27. }
  28. if finfo.Size() == 0 {
  29. return nil
  30. }
  31. return json.NewDecoder(f).Decode(&HOSTS)
  32. }
  33. // watch the hosts file for any changes and the reload it
  34. func WatchChanges() {
  35. watcher, err := fsnotify.NewWatcher()
  36. if err != nil {
  37. return
  38. }
  39. defer watcher.Close()
  40. watcher.Add(*HOSTS_FILE)
  41. for {
  42. select {
  43. case <-watcher.Events:
  44. colorize(color.FgYellow, "⇛ There is a change in the hosts file, reloading ...")
  45. if err := InitHostsList(); err != nil {
  46. colorize(color.FgRed, "⇛", err.Error())
  47. } else {
  48. colorize(color.FgGreen, "⇛ The hosts file has been reloaded successfully!")
  49. }
  50. }
  51. }
  52. }