Make it possible to call service.Init multiple times

This commit is contained in:
Asim 2016-05-06 12:21:41 +01:00
parent b13361d010
commit 8b76e277bc

View File

@ -14,6 +14,8 @@ import (
type service struct { type service struct {
opts Options opts Options
init chan bool
} }
func newService(opts ...Option) Service { func newService(opts ...Option) Service {
@ -28,6 +30,7 @@ func newService(opts ...Option) Service {
return &service{ return &service{
opts: options, opts: options,
init: make(chan bool),
} }
} }
@ -49,24 +52,36 @@ func (s *service) run(exit chan bool) {
} }
} }
// Init initialises options. Additionally it calls cmd.Init
// which parses command line flags. cmd.Init is only called
// on first Init.
func (s *service) Init(opts ...Option) { func (s *service) Init(opts ...Option) {
// We might get more command flags or the action here // If <-s.init blocks, Init has not been called yet
// This is pretty ugly, find a better way // so we can call cmd.Init once.
options := newOptions() select {
options.Cmd = s.opts.Cmd case <-s.init:
for _, o := range opts { default:
o(&options) // close init
} close(s.init)
s.opts.Cmd = options.Cmd
// Initialise the command flags, overriding new service // We might get more command flags or the action here
s.opts.Cmd.Init( // This is pretty ugly, find a better way
cmd.Broker(&s.opts.Broker), options := newOptions()
cmd.Registry(&s.opts.Registry), options.Cmd = s.opts.Cmd
cmd.Transport(&s.opts.Transport), for _, o := range opts {
cmd.Client(&s.opts.Client), o(&options)
cmd.Server(&s.opts.Server), }
) s.opts.Cmd = options.Cmd
// Initialise the command flags, overriding new service
s.opts.Cmd.Init(
cmd.Broker(&s.opts.Broker),
cmd.Registry(&s.opts.Registry),
cmd.Transport(&s.opts.Transport),
cmd.Client(&s.opts.Client),
cmd.Server(&s.opts.Server),
)
}
// Update any options to override command flags // Update any options to override command flags
for _, o := range opts { for _, o := range opts {