allow to override Struct on Save/Load/Init

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2023-03-15 00:53:26 +03:00
parent 26991e2ea2
commit d6cba44b60
2 changed files with 48 additions and 4 deletions

46
flag.go
View File

@ -43,13 +43,26 @@ func (c *flagConfig) Init(opts ...config.Option) error {
for _, o := range opts {
o(&c.opts)
}
if err := config.DefaultBeforeInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
c.configure()
fields, err := rutil.StructFields(c.opts.Struct)
if err != nil {
if !c.opts.AllowFail {
return err
}
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}
for _, sf := range fields {
tf, ok := sf.Field.Tag.Lookup(c.opts.StructTag)
if !ok {
@ -84,10 +97,13 @@ func (c *flagConfig) Init(opts ...config.Option) error {
}
if err != nil {
c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err)
if !c.opts.AllowFail {
return err
}
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}
@ -120,26 +136,52 @@ func (c *flagConfig) Init(opts ...config.Option) error {
err = c.flagMap(sf.Value, fn, fv, fd)
}
if err != nil {
c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err)
if !c.opts.AllowFail {
return err
}
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}
}
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}
func (c *flagConfig) Load(ctx context.Context, opts ...config.LoadOption) error {
options := config.NewLoadOptions(opts...)
_ = options
if err := config.DefaultBeforeLoad(ctx, c); err != nil && !c.opts.AllowFail {
return err
}
if err := config.DefaultAfterLoad(ctx, c); err != nil && !c.opts.AllowFail {
return err
}
// TODO: allow merge, append and so
flag.Parse()
return nil
}
func (c *flagConfig) Save(ctx context.Context, opts ...config.SaveOption) error {
if err := config.DefaultBeforeSave(ctx, c); err != nil && !c.opts.AllowFail {
return err
}
if err := config.DefaultAfterSave(ctx, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}

4
go.mod
View File

@ -1,5 +1,7 @@
module go.unistack.org/micro-config-flag/v3
go 1.16
go 1.18
require go.unistack.org/micro/v3 v3.10.16
require github.com/imdario/mergo v0.3.13 // indirect