83 lines
2.2 KiB
Go
Raw Normal View History

2019-09-09 09:20:17 -07:00
package handler
import (
"context"
"time"
2019-09-09 09:20:17 -07:00
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/service"
2019-10-13 12:23:13 +01:00
pb "github.com/micro/go-micro/registry/service/proto"
2019-09-09 09:20:17 -07:00
)
type Registry struct {
// internal registry
Registry registry.Registry
}
2019-09-09 09:25:47 -07:00
func (r *Registry) GetService(ctx context.Context, req *pb.GetRequest, rsp *pb.GetResponse) error {
2019-09-09 09:20:17 -07:00
services, err := r.Registry.GetService(req.Service)
2019-09-09 09:25:47 -07:00
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
2019-09-09 09:20:17 -07:00
for _, srv := range services {
rsp.Services = append(rsp.Services, service.ToProto(srv))
}
return nil
}
2019-09-09 09:25:47 -07:00
func (r *Registry) Register(ctx context.Context, req *pb.Service, rsp *pb.EmptyResponse) error {
var regOpts []registry.RegisterOption
2019-09-29 15:03:21 +01:00
if req.Options != nil {
ttl := time.Duration(req.Options.Ttl) * time.Second
regOpts = append(regOpts, registry.RegisterTTL(ttl))
}
err := r.Registry.Register(service.ToService(req), regOpts...)
2019-09-09 09:20:17 -07:00
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
2019-09-09 09:20:17 -07:00
return nil
}
2019-09-09 09:25:47 -07:00
func (r *Registry) Deregister(ctx context.Context, req *pb.Service, rsp *pb.EmptyResponse) error {
err := r.Registry.Deregister(service.ToService(req))
2019-09-09 09:20:17 -07:00
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
return nil
}
2019-09-09 09:25:47 -07:00
func (r *Registry) ListServices(ctx context.Context, req *pb.ListRequest, rsp *pb.ListResponse) error {
2019-09-09 09:20:17 -07:00
services, err := r.Registry.ListServices()
2019-09-09 09:25:47 -07:00
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
2019-09-09 09:20:17 -07:00
for _, srv := range services {
rsp.Services = append(rsp.Services, service.ToProto(srv))
}
return nil
}
2019-09-09 09:25:47 -07:00
func (r *Registry) Watch(ctx context.Context, req *pb.WatchRequest, rsp pb.Registry_WatchStream) error {
watcher, err := r.Registry.Watch(registry.WatchService(req.Service))
2019-09-09 09:20:17 -07:00
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
for {
next, err := watcher.Next()
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
err = rsp.Send(&pb.Result{
Action: next.Action,
Service: service.ToProto(next.Service),
})
if err != nil {
return errors.InternalServerError("go.micro.registry", err.Error())
}
}
}