gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/config/source/memory/memory.go (about) 1 // Package memory is a memory source 2 package memory 3 4 import ( 5 "sync" 6 "time" 7 8 "github.com/google/uuid" 9 "gitee.com/liuxuezhan/go-micro-v1.18.0/config/source" 10 ) 11 12 type memory struct { 13 sync.RWMutex 14 ChangeSet *source.ChangeSet 15 Watchers map[string]*watcher 16 } 17 18 func (s *memory) Read() (*source.ChangeSet, error) { 19 s.RLock() 20 cs := &source.ChangeSet{ 21 Format: s.ChangeSet.Format, 22 Timestamp: s.ChangeSet.Timestamp, 23 Data: s.ChangeSet.Data, 24 Checksum: s.ChangeSet.Checksum, 25 Source: s.ChangeSet.Source, 26 } 27 s.RUnlock() 28 return cs, nil 29 } 30 31 func (s *memory) Watch() (source.Watcher, error) { 32 w := &watcher{ 33 Id: uuid.New().String(), 34 Updates: make(chan *source.ChangeSet, 100), 35 Source: s, 36 } 37 38 s.Lock() 39 s.Watchers[w.Id] = w 40 s.Unlock() 41 return w, nil 42 } 43 44 // Update allows manual updates of the config data. 45 func (s *memory) Update(c *source.ChangeSet) { 46 // don't process nil 47 if c == nil { 48 return 49 } 50 51 // hash the file 52 s.Lock() 53 // update changeset 54 s.ChangeSet = &source.ChangeSet{ 55 Data: c.Data, 56 Format: c.Format, 57 Source: "memory", 58 Timestamp: time.Now(), 59 } 60 s.ChangeSet.Checksum = s.ChangeSet.Sum() 61 62 // update watchers 63 for _, w := range s.Watchers { 64 select { 65 case w.Updates <- s.ChangeSet: 66 default: 67 } 68 } 69 s.Unlock() 70 } 71 72 func (s *memory) String() string { 73 return "memory" 74 } 75 76 func NewSource(opts ...source.Option) source.Source { 77 var options source.Options 78 for _, o := range opts { 79 o(&options) 80 } 81 82 s := &memory{ 83 Watchers: make(map[string]*watcher), 84 } 85 86 if options.Context != nil { 87 c, ok := options.Context.Value(changeSetKey{}).(*source.ChangeSet) 88 if ok { 89 s.Update(c) 90 } 91 } 92 93 return s 94 }