go-micro.dev/v5@v5.12.0/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" 6 "io/fs" 7 "os" 8 9 "go-micro.dev/v5/config/source" 10 ) 11 12 type file struct { 13 opts source.Options 14 fs fs.FS 15 path string 16 } 17 18 var ( 19 DefaultPath = "config.json" 20 ) 21 22 func (f *file) Read() (*source.ChangeSet, error) { 23 var fh fs.File 24 var err error 25 26 if f.fs != nil { 27 fh, err = f.fs.Open(f.path) 28 } else { 29 fh, err = os.Open(f.path) 30 } 31 32 if err != nil { 33 return nil, err 34 } 35 defer fh.Close() 36 b, err := io.ReadAll(fh) 37 if err != nil { 38 return nil, err 39 } 40 info, err := fh.Stat() 41 if err != nil { 42 return nil, err 43 } 44 45 cs := &source.ChangeSet{ 46 Format: format(f.path, f.opts.Encoder), 47 Source: f.String(), 48 Timestamp: info.ModTime(), 49 Data: b, 50 } 51 cs.Checksum = cs.Sum() 52 53 return cs, nil 54 } 55 56 func (f *file) String() string { 57 return "file" 58 } 59 60 func (f *file) Watch() (source.Watcher, error) { 61 // do not watch if fs.FS instance is provided 62 if f.fs != nil { 63 return source.NewNoopWatcher() 64 } 65 66 if _, err := os.Stat(f.path); err != nil { 67 return nil, err 68 } 69 return newWatcher(f) 70 } 71 72 func (f *file) Write(cs *source.ChangeSet) error { 73 return nil 74 } 75 76 func NewSource(opts ...source.Option) source.Source { 77 options := source.NewOptions(opts...) 78 79 fs, _ := options.Context.Value(fsKey{}).(fs.FS) 80 81 path := DefaultPath 82 f, ok := options.Context.Value(filePathKey{}).(string) 83 if ok { 84 path = f 85 } 86 return &file{opts: options, fs: fs, path: path} 87 }