Ai
1 Star 0 Fork 0

monobytes/gcore

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
watcher.go 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
null 提交于 2025-01-22 18:29 +08:00 . first commit
package etcd
import (
"context"
"gitee.com/monobytes/gcore/gconfig"
"go.etcd.io/etcd/api/v3/mvccpb"
"go.etcd.io/etcd/client/v3"
"path/filepath"
"strings"
)
type watcher struct {
ctx context.Context
cancel context.CancelFunc
source *Source
watcher clientv3.Watcher
chWatch clientv3.WatchChan
}
func newWatcher(ctx context.Context, s *Source) (gconfig.Watcher, error) {
w := &watcher{}
w.ctx, w.cancel = context.WithCancel(ctx)
w.source = s
w.watcher = clientv3.NewWatcher(w.source.opts.client)
w.chWatch = w.watcher.Watch(w.ctx, w.source.opts.path, clientv3.WithPrefix())
return w, nil
}
// Next 返回服务实例列表
func (w *watcher) Next() ([]*gconfig.Configuration, error) {
select {
case <-w.ctx.Done():
return nil, w.ctx.Err()
case res, ok := <-w.chWatch:
if !ok {
if err := w.ctx.Err(); err != nil {
return nil, err
}
}
if res.Err() != nil {
return nil, res.Err()
}
configs := make([]*gconfig.Configuration, 0, len(res.Events))
for _, ev := range res.Events {
switch ev.Type {
case mvccpb.PUT:
fullPath := string(ev.Kv.Key)
path := strings.TrimPrefix(fullPath, w.source.opts.path)
file := filepath.Base(fullPath)
ext := filepath.Ext(file)
configs = append(configs, &gconfig.Configuration{
Path: path,
File: file,
Name: strings.TrimSuffix(file, ext),
Format: strings.TrimPrefix(ext, "."),
Content: ev.Kv.Value,
FullPath: fullPath,
})
}
}
return configs, nil
}
}
// Stop 停止监听
func (w *watcher) Stop() error {
w.cancel()
return w.watcher.Close()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/monobytes/gcore.git
git@gitee.com:monobytes/gcore.git
monobytes
gcore
gcore
v1.0.1

搜索帮助