file.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Package file is a file source. Expected format is json
  2. package file
  3. import (
  4. "io/ioutil"
  5. "os"
  6. "gogs.baozhida.cn/zoie/OAuth-core/config/source"
  7. )
  8. type file struct {
  9. path string
  10. opts source.Options
  11. }
  12. var (
  13. DefaultPath = "config.json"
  14. )
  15. func (f *file) Read() (*source.ChangeSet, error) {
  16. fh, err := os.Open(f.path)
  17. if err != nil {
  18. return nil, err
  19. }
  20. defer fh.Close()
  21. b, err := ioutil.ReadAll(fh)
  22. if err != nil {
  23. return nil, err
  24. }
  25. info, err := fh.Stat()
  26. if err != nil {
  27. return nil, err
  28. }
  29. cs := &source.ChangeSet{
  30. Format: format(f.path, f.opts.Encoder),
  31. Source: f.String(),
  32. Timestamp: info.ModTime(),
  33. Data: b,
  34. }
  35. cs.Checksum = cs.Sum()
  36. return cs, nil
  37. }
  38. func (f *file) String() string {
  39. return "file"
  40. }
  41. func (f *file) Watch() (source.Watcher, error) {
  42. if _, err := os.Stat(f.path); err != nil {
  43. return nil, err
  44. }
  45. return newWatcher(f)
  46. }
  47. func (f *file) Write(cs *source.ChangeSet) error {
  48. return nil
  49. }
  50. func NewSource(opts ...source.Option) source.Source {
  51. options := source.NewOptions(opts...)
  52. path := DefaultPath
  53. f, ok := options.Context.Value(filePathKey{}).(string)
  54. if ok {
  55. path = f
  56. }
  57. return &file{opts: options, path: path}
  58. }