1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-24 10:07:04 +02:00
go-micro/config/source/service/service.go

74 lines
1.4 KiB
Go
Raw Normal View History

package service
2020-01-16 18:10:15 +02:00
import (
"context"
2020-01-17 15:32:00 +02:00
"github.com/micro/go-micro/client"
2020-01-16 18:10:15 +02:00
"github.com/micro/go-micro/config/source"
proto "github.com/micro/go-micro/config/source/service/proto"
2020-01-16 18:10:15 +02:00
"github.com/micro/go-micro/util/log"
)
var (
2020-01-18 17:16:23 +02:00
DefaultName = "go.micro.config"
DefaultClient = client.DefaultClient
2020-01-16 18:10:15 +02:00
)
2020-01-17 17:27:41 +02:00
type service struct {
2020-01-16 18:10:15 +02:00
serviceName string
key string
opts source.Options
2020-01-17 17:27:41 +02:00
client proto.Service
2020-01-16 18:10:15 +02:00
}
2020-01-17 17:27:41 +02:00
func (m *service) Read() (set *source.ChangeSet, err error) {
2020-01-16 18:10:15 +02:00
req, err := m.client.Read(context.Background(), &proto.ReadRequest{Path: m.key})
if err != nil {
return nil, err
}
return toChangeSet(req.Change.ChangeSet), nil
}
2020-01-17 17:27:41 +02:00
func (m *service) Watch() (w source.Watcher, err error) {
2020-01-16 18:10:15 +02:00
stream, err := m.client.Watch(context.Background(), &proto.WatchRequest{Key: m.key})
if err != nil {
log.Error("watch err: ", err)
return
}
return newWatcher(stream)
}
// Write is unsupported
2020-01-17 17:27:41 +02:00
func (m *service) Write(cs *source.ChangeSet) error {
2020-01-16 18:10:15 +02:00
return nil
}
2020-01-17 17:27:41 +02:00
func (m *service) String() string {
2020-01-18 17:16:23 +02:00
return "service"
2020-01-16 18:10:15 +02:00
}
func NewSource(opts ...source.Option) source.Source {
var options source.Options
for _, o := range opts {
o(&options)
}
2020-01-18 17:16:23 +02:00
addr := DefaultName
2020-01-16 18:10:15 +02:00
if options.Context != nil {
a, ok := options.Context.Value(serviceNameKey{}).(string)
if ok {
addr = a
}
}
2020-01-17 17:27:41 +02:00
s := &service{
2020-01-16 18:10:15 +02:00
serviceName: addr,
opts: options,
2020-01-17 17:27:41 +02:00
client: proto.NewService(addr, DefaultClient),
2020-01-16 18:10:15 +02:00
}
return s
}