add before&after hooks (#751)

* add before&after hooks
pull/752/head
Tony Chen 4 years ago committed by GitHub
parent 26cf7c80ad
commit 50af5b2588
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 10
      app.go
  2. 1
      encoding/json/json.go
  3. 13
      options.go

@ -80,6 +80,11 @@ func (a *App) Run() error {
return srv.Start()
})
}
for _, fn := range a.opts.before {
if err := fn(); err != nil {
return err
}
}
if a.opts.registrar != nil {
if err := a.opts.registrar.Register(a.opts.ctx, a.instance); err != nil {
return err
@ -113,6 +118,11 @@ func (a *App) Stop() error {
if a.cancel != nil {
a.cancel()
}
for _, fn := range a.opts.after {
if err := fn(); err != nil {
return err
}
}
return nil
}

@ -44,7 +44,6 @@ func (codec) Unmarshal(data []byte, v interface{}) error {
if rv.IsNil() {
rv.Set(reflect.New(rv.Type().Elem()))
v = rv.Interface()
break
}
rv = rv.Elem()
}

@ -27,6 +27,9 @@ type options struct {
registrar registry.Registrar
servers []transport.Server
before []func() error
after []func() error
}
// ID with service id.
@ -78,3 +81,13 @@ func Registry(r registry.Registrar) Option {
func Server(srv ...transport.Server) Option {
return func(o *options) { o.servers = srv }
}
// Before before service starts.
func Before(fn func() error) Option {
return func(o *options) { o.before = append(o.before, fn) }
}
// After after services stops.
func After(fn func() error) Option {
return func(o *options) { o.after = append(o.after, fn) }
}

Loading…
Cancel
Save