From 1bacad1fe8cc7cb308da55670124d3597e7dc253 Mon Sep 17 00:00:00 2001 From: "Tobias Wellnitz, DH1TW" Date: Sat, 6 Jan 2018 13:10:43 +0100 Subject: [PATCH] simplified nats Option injection via Context --- nats.go | 19 ++++++++++--------- nats_test.go | 2 +- options.go | 24 +++++++++--------------- 3 files changed, 20 insertions(+), 25 deletions(-) diff --git a/nats.go b/nats.go index e3cb897..0b0544e 100644 --- a/nats.go +++ b/nats.go @@ -170,38 +170,39 @@ func (n *nbroker) String() string { func NewBroker(opts ...broker.Option) broker.Broker { - bopts := &brokerOptions{ - natsOptions: DefaultNatsOptions, - } - options := broker.Options{ // Default codec Codec: json.NewCodec(), - Context: context.WithValue(context.Background(), optionsKey, bopts), + Context: context.Background(), } for _, o := range opts { o(&options) } + natsOptions := nats.GetDefaultOptions() + if n, ok := options.Context.Value(optionsKey{}).(nats.Options); ok { + natsOptions = n + } + // broker.Options have higher priority than nats.Options // only if Addrs, Secure or TLSConfig were not set through a broker.Option // we read them from nats.Option if len(options.Addrs) == 0 { - options.Addrs = bopts.natsOptions.Servers + options.Addrs = natsOptions.Servers } if !options.Secure { - options.Secure = bopts.natsOptions.Secure + options.Secure = natsOptions.Secure } if options.TLSConfig == nil { - options.TLSConfig = bopts.natsOptions.TLSConfig + options.TLSConfig = natsOptions.TLSConfig } nb := &nbroker{ opts: options, - nopts: bopts.natsOptions, + nopts: natsOptions, addrs: setAddrs(options.Addrs), } diff --git a/nats_test.go b/nats_test.go index 554be94..c95f57a 100644 --- a/nats_test.go +++ b/nats_test.go @@ -67,7 +67,7 @@ func TestInitAddrs(t *testing.T) { case "natsOptionConstructor": nopts := nats.GetDefaultOptions() nopts.Servers = addrs - br = NewBroker(NatsOptions(nopts)) + br = NewBroker(Options(nopts)) br.Init() case "default": br = NewBroker() diff --git a/options.go b/options.go index 06bfd79..bd8bb51 100644 --- a/options.go +++ b/options.go @@ -1,27 +1,21 @@ package nats import ( + "context" + "github.com/micro/go-micro/broker" "github.com/nats-io/nats" ) -var ( - DefaultNatsOptions = nats.GetDefaultOptions() +type optionsKey struct{} - optionsKey = optionsKeyType{} -) - -type optionsKeyType struct{} - -type brokerOptions struct { - natsOptions nats.Options -} - -// NatsOptions allow to inject a nats.Options struct for configuring +// Options allow to inject a nats.Options struct for configuring // the nats connection -func NatsOptions(nopts nats.Options) broker.Option { +func Options(nopts nats.Options) broker.Option { return func(o *broker.Options) { - no := o.Context.Value(optionsKey).(*brokerOptions) - no.natsOptions = nopts + if o.Context == nil { + o.Context = context.Background() + } + o.Context = context.WithValue(o.Context, optionsKey{}, nopts) } }