file.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package paladin
  2. import (
  3. "context"
  4. "errors"
  5. "io/ioutil"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. )
  10. var _ Client = &file{}
  11. // file is file config client.
  12. type file struct {
  13. ch chan Event
  14. values *Map
  15. }
  16. // NewFile new a config file client.
  17. // conf = /data/conf/app/
  18. // conf = /data/conf/app/xxx.toml
  19. func NewFile(base string) (Client, error) {
  20. // paltform slash
  21. base = filepath.FromSlash(base)
  22. fi, err := os.Stat(base)
  23. if err != nil {
  24. panic(err)
  25. }
  26. // dirs or file to paths
  27. var paths []string
  28. if fi.IsDir() {
  29. files, err := ioutil.ReadDir(base)
  30. if err != nil {
  31. panic(err)
  32. }
  33. for _, file := range files {
  34. if !file.IsDir() {
  35. paths = append(paths, path.Join(base, file.Name()))
  36. }
  37. }
  38. } else {
  39. paths = append(paths, base)
  40. }
  41. // laod config file to values
  42. values := make(map[string]*Value, len(paths))
  43. for _, file := range paths {
  44. if file == "" {
  45. return nil, errors.New("paladin: path is empty")
  46. }
  47. b, err := ioutil.ReadFile(file)
  48. if err != nil {
  49. return nil, err
  50. }
  51. s := string(b)
  52. values[path.Base(file)] = &Value{val: s, raw: s}
  53. }
  54. m := new(Map)
  55. m.Store(values)
  56. return &file{values: m, ch: make(chan Event, 10)}, nil
  57. }
  58. // Get return value by key.
  59. func (f *file) Get(key string) *Value {
  60. return f.values.Get(key)
  61. }
  62. // GetAll return value map.
  63. func (f *file) GetAll() *Map {
  64. return f.values
  65. }
  66. // WatchEvent watch multi key.
  67. func (f *file) WatchEvent(ctx context.Context, key ...string) <-chan Event {
  68. return f.ch
  69. }
  70. // Close close watcher.
  71. func (f *file) Close() error {
  72. close(f.ch)
  73. return nil
  74. }