1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-02-19 19:10:08 +02:00
kratos/contrib/config/etcd/watcher.go
Cluas 6fa5700c3c
chore(contrib/config): uniformly canceled by CancelFunc (#2111)
* chore: remove sentinel error for compatibility

* chore: core use lssentinel error

* chore: uniformly canceled by CancelFunc

* chore: remove error
2022-06-17 23:42:32 +08:00

51 lines
856 B
Go

package etcd
import (
"context"
"github.com/go-kratos/kratos/v2/config"
clientv3 "go.etcd.io/etcd/client/v3"
)
type watcher struct {
source *source
ch clientv3.WatchChan
ctx context.Context
cancel context.CancelFunc
}
func newWatcher(s *source) *watcher {
ctx, cancel := context.WithCancel(context.Background())
w := &watcher{
source: s,
ctx: ctx,
cancel: cancel,
}
var opts []clientv3.OpOption
if s.options.prefix {
opts = append(opts, clientv3.WithPrefix())
}
w.ch = s.client.Watch(s.options.ctx, s.options.path, opts...)
return w
}
func (w *watcher) Next() ([]*config.KeyValue, error) {
select {
case resp := <-w.ch:
if resp.Err() != nil {
return nil, resp.Err()
}
return w.source.Load()
case <-w.ctx.Done():
return nil, w.ctx.Err()
}
}
func (w *watcher) Stop() error {
w.cancel()
return nil
}