config package rework (#9)
* change config interface * reuse codec * allow to modify next config based on values in current config via BeforeLoad Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
@@ -1,28 +1,88 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/unistack-org/micro/v3/config/loader"
|
||||
"github.com/unistack-org/micro/v3/config/reader"
|
||||
"github.com/unistack-org/micro/v3/config/source"
|
||||
"context"
|
||||
|
||||
"github.com/unistack-org/micro/v3/codec"
|
||||
)
|
||||
|
||||
// WithLoader sets the loader for manager config
|
||||
func WithLoader(l loader.Loader) Option {
|
||||
type Options struct {
|
||||
BeforeLoad []func(context.Context, Config) error
|
||||
AfterLoad []func(context.Context, Config) error
|
||||
BeforeSave []func(context.Context, Config) error
|
||||
AfterSave []func(context.Context, Config) error
|
||||
// Struct that holds config data
|
||||
Struct interface{}
|
||||
// struct tag name
|
||||
StructTag string
|
||||
// codec that used for load/save
|
||||
Codec codec.Codec
|
||||
// for alternative data
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Context: context.Background(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
func BeforeLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.Loader = l
|
||||
o.BeforeLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// WithSource appends a source to list of sources
|
||||
func WithSource(s source.Source) Option {
|
||||
func AfterLoad(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.Source = append(o.Source, s)
|
||||
o.AfterLoad = fn
|
||||
}
|
||||
}
|
||||
|
||||
// WithReader sets the config reader
|
||||
func WithReader(r reader.Reader) Option {
|
||||
func BeforeSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.Reader = r
|
||||
o.BeforeSave = fn
|
||||
}
|
||||
}
|
||||
|
||||
func AfterSave(fn ...func(context.Context, Config) error) Option {
|
||||
return func(o *Options) {
|
||||
o.AfterSave= fn
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
func Context(ctx context.Context) Option {
|
||||
return func(o *Options) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// Codec sets the source codec
|
||||
func Codec(c codec.Codec) Option {
|
||||
return func(o *Options) {
|
||||
o.Codec = c
|
||||
}
|
||||
}
|
||||
|
||||
// Struct
|
||||
func Struct(v interface{}) Option {
|
||||
return func(o *Options) {
|
||||
o.Struct = v
|
||||
}
|
||||
}
|
||||
|
||||
// StructTag
|
||||
func StructTag(name string) Option {
|
||||
return func(o *Options) {
|
||||
o.StructTag = name
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user