micro/config/source/service/service.go

91 lines
1.8 KiB
Go
Raw Normal View History

package service
2020-01-16 19:10:15 +03:00
import (
"context"
"github.com/micro/go-micro/v2/client"
"github.com/micro/go-micro/v2/config/source"
proto "github.com/micro/go-micro/v2/config/source/service/proto"
log "github.com/micro/go-micro/v2/logger"
2020-01-16 19:10:15 +03:00
)
var (
2020-01-18 18:16:23 +03:00
DefaultName = "go.micro.config"
2020-01-20 13:31:18 +03:00
DefaultKey = "NAMESPACE:CONFIG"
DefaultPath = ""
2020-01-18 18:16:23 +03:00
DefaultClient = client.DefaultClient
2020-01-16 19:10:15 +03:00
)
2020-01-17 18:27:41 +03:00
type service struct {
2020-01-16 19:10:15 +03:00
serviceName string
key string
2020-01-20 13:31:18 +03:00
path string
2020-01-16 19:10:15 +03:00
opts source.Options
2020-01-23 14:37:54 +03:00
client proto.ConfigService
2020-01-16 19:10:15 +03:00
}
2020-01-17 18:27:41 +03:00
func (m *service) Read() (set *source.ChangeSet, err error) {
2020-01-20 13:31:18 +03:00
req, err := m.client.Read(context.Background(), &proto.ReadRequest{Key: m.key, Path: m.path})
2020-01-16 19:10:15 +03:00
if err != nil {
return nil, err
}
return toChangeSet(req.Change.ChangeSet), nil
}
2020-01-17 18:27:41 +03:00
func (m *service) Watch() (w source.Watcher, err error) {
2020-01-20 13:31:18 +03:00
stream, err := m.client.Watch(context.Background(), &proto.WatchRequest{Key: m.key, Path: m.path})
2020-01-16 19:10:15 +03:00
if err != nil {
log.Error("watch err: ", err)
return
}
return newWatcher(stream)
}
// Write is unsupported
2020-01-17 18:27:41 +03:00
func (m *service) Write(cs *source.ChangeSet) error {
2020-01-16 19:10:15 +03:00
return nil
}
2020-01-17 18:27:41 +03:00
func (m *service) String() string {
2020-01-18 18:16:23 +03:00
return "service"
2020-01-16 19:10:15 +03:00
}
func NewSource(opts ...source.Option) source.Source {
var options source.Options
for _, o := range opts {
o(&options)
}
2020-01-18 18:16:23 +03:00
addr := DefaultName
2020-01-20 13:31:18 +03:00
key := DefaultKey
path := DefaultPath
2020-01-16 19:10:15 +03:00
if options.Context != nil {
a, ok := options.Context.Value(serviceNameKey{}).(string)
if ok {
addr = a
}
2020-01-20 13:31:18 +03:00
k, ok := options.Context.Value(keyKey{}).(string)
if ok {
key = k
}
p, ok := options.Context.Value(pathKey{}).(string)
if ok {
path = p
}
2020-01-16 19:10:15 +03:00
}
2020-01-17 18:27:41 +03:00
s := &service{
2020-01-16 19:10:15 +03:00
serviceName: addr,
opts: options,
2020-01-20 13:31:18 +03:00
key: key,
path: path,
2020-01-23 14:37:54 +03:00
client: proto.NewConfigService(addr, DefaultClient),
2020-01-16 19:10:15 +03:00
}
return s
}