handle before/after inside config implementations

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-12-18 03:37:18 +03:00
parent f6c0728a59
commit 8c504bd029
2 changed files with 35 additions and 0 deletions

View File

@ -40,3 +40,14 @@ type Config interface {
// Next() (, error)
// Stop() error
//}
// Load loads config from config sources
func Load(ctx context.Context, cs ...Config) error {
var err error
for _, c := range cs {
if err = c.Load(ctx); err != nil {
return err
}
}
return nil
}

View File

@ -23,12 +23,24 @@ func (c *defaultConfig) Init(opts ...Option) error {
}
func (c *defaultConfig) Load(ctx context.Context) error {
for _, fn := range c.opts.BeforeLoad {
if err := fn(ctx, c); err != nil {
return err
}
}
valueOf := reflect.ValueOf(c.opts.Struct)
if err := c.fillValues(ctx, valueOf); err != nil {
return err
}
for _, fn := range c.opts.AfterLoad {
if err := fn(ctx, c); err != nil {
return err
}
}
return nil
}
@ -208,6 +220,18 @@ func (c *defaultConfig) fillValues(ctx context.Context, valueOf reflect.Value) e
}
func (c *defaultConfig) Save(ctx context.Context) error {
for _, fn := range c.opts.BeforeSave {
if err := fn(ctx, c); err != nil {
return err
}
}
for _, fn := range c.opts.AfterSave {
if err := fn(ctx, c); err != nil {
return err
}
}
return nil
}