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