diff --git a/registry/service/util.go b/registry/service/util.go index 4ba5f4da..3d6c681d 100644 --- a/registry/service/util.go +++ b/registry/service/util.go @@ -1,6 +1,8 @@ package service import ( + "strings" + "github.com/micro/go-micro/v2/registry" pb "github.com/micro/go-micro/v2/registry/service/proto" ) @@ -37,6 +39,10 @@ func toValues(v []*pb.Value) []*registry.Value { return vs } +// NameSeperator is the string which is used as a seperator when joinin +// namespace to the service name +const NameSeperator = "/" + func ToProto(s *registry.Service) *pb.Service { endpoints := make([]*pb.Endpoint, 0, len(s.Endpoints)) for _, ep := range s.Endpoints { @@ -76,8 +82,14 @@ func ToProto(s *registry.Service) *pb.Service { }) } + // the service name will contain the namespace, e.g. + // 'default/go.micro.service.foo'. Remove the namespace + // using the following: + comps := strings.Split(s.Name, NameSeperator) + name := comps[len(comps)-1] + return &pb.Service{ - Name: s.Name, + Name: name, Version: s.Version, Metadata: s.Metadata, Endpoints: endpoints, @@ -86,7 +98,12 @@ func ToProto(s *registry.Service) *pb.Service { } } -func ToService(s *pb.Service) *registry.Service { +func ToService(s *pb.Service, opts ...Option) *registry.Service { + var options Options + for _, o := range opts { + o(&options) + } + endpoints := make([]*registry.Endpoint, 0, len(s.Endpoints)) for _, ep := range s.Endpoints { var request, response *registry.Value @@ -124,11 +141,34 @@ func ToService(s *pb.Service) *registry.Service { }) } + // add the namespace to the name + var name string + if len(options.Namespace) > 0 { + name = strings.Join([]string{options.Namespace, s.Name}, NameSeperator) + } else { + name = s.Name + } + return ®istry.Service{ - Name: s.Name, + Name: name, Version: s.Version, Metadata: s.Metadata, Endpoints: endpoints, Nodes: nodes, } } + +// Options for marshaling / unmarshaling services +type Options struct { + Namespace string +} + +// Option is a function which sets options +type Option func(o *Options) + +// WithNamespace sets the namespace option +func WithNamespace(ns string) Option { + return func(o *Options) { + o.Namespace = ns + } +} diff --git a/util/wrapper/wrapper.go b/util/wrapper/wrapper.go index ee569ef2..dba8d274 100644 --- a/util/wrapper/wrapper.go +++ b/util/wrapper/wrapper.go @@ -276,7 +276,9 @@ func AuthHandler(fn func() auth.Auth) server.HandlerWrapper { } // There is an account, set it in the context - ctx = auth.ContextWithAccount(ctx, account) + if len(account.ID) > 0 { + ctx = auth.ContextWithAccount(ctx, account) + } // The user is authorised, allow the call return h(ctx, req, rsp)