From c58ac35dfc1b5bc480d560b61dcdc4c75959fb9d Mon Sep 17 00:00:00 2001 From: ben-toogood Date: Thu, 2 Jul 2020 17:54:53 +0100 Subject: [PATCH] broker/service: use wrapped micro client to authenticate requests (#1782) --- broker/service/options.go | 22 ++++++++++++++++++++++ broker/service/service.go | 6 ++++++ config/cmd/cmd.go | 2 +- 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 broker/service/options.go diff --git a/broker/service/options.go b/broker/service/options.go new file mode 100644 index 00000000..41e5b403 --- /dev/null +++ b/broker/service/options.go @@ -0,0 +1,22 @@ +package service + +import ( + "context" + + "github.com/micro/go-micro/v2/broker" + "github.com/micro/go-micro/v2/client" +) + +type clientKey struct{} + +// Client to call broker service +func Client(c client.Client) broker.Option { + return func(o *broker.Options) { + if o.Context == nil { + o.Context = context.WithValue(context.Background(), clientKey{}, c) + return + } + + o.Context = context.WithValue(o.Context, clientKey{}, c) + } +} diff --git a/broker/service/service.go b/broker/service/service.go index 0ce2f00e..f5708746 100644 --- a/broker/service/service.go +++ b/broker/service/service.go @@ -138,6 +138,12 @@ func NewBroker(opts ...broker.Option) broker.Broker { cli := client.DefaultClient + // get options client from the context. We set this in the context to prevent an import loop, as + // the client depends on the broker + if c, ok := options.Context.Value(clientKey{}).(client.Client); ok { + cli = c + } + return &serviceBroker{ Addrs: addrs, Client: pb.NewBrokerService(DefaultName, cli), diff --git a/config/cmd/cmd.go b/config/cmd/cmd.go index 4dc16edf..ff0faebc 100644 --- a/config/cmd/cmd.go +++ b/config/cmd/cmd.go @@ -643,7 +643,7 @@ func (c *cmd) Before(ctx *cli.Context) error { } // Setup broker options. - brokerOpts := []broker.Option{} + brokerOpts := []broker.Option{brokerSrv.Client(microClient)} if len(ctx.String("broker_address")) > 0 { brokerOpts = append(brokerOpts, broker.Addrs(ctx.String("broker_address"))) }