Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: custom func #12

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion config/custom_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,18 @@ import (

type CustomConfig struct {
ConfigMap map[string]interface{} `yaml:"config-map" json:"config-map,omitempty" property:"config-map"`
Functions []CustomFunc
}

func (*CustomConfig) Prefix() string {
return constant.CustomConfigPrefix
}

func (c *CustomConfig) Init() error {
return c.check()
if err := c.check(); err != nil {
return err
}
return c.runCustomFunc()
}

func (c *CustomConfig) check() error {
Expand All @@ -51,6 +55,15 @@ func (c *CustomConfig) GetDefineValue(key string, default_value interface{}) int
return default_value
}

func (c *CustomConfig) runCustomFunc() error {
for _, f := range c.Functions {
if err := f(rootConfig); err != nil {
return err
}
}
return nil
}

func GetDefineValue(key string, default_value interface{}) interface{} {
rt := GetRootConfig()
if rt.Custom == nil {
Expand All @@ -75,6 +88,14 @@ func (ccb *CustomConfigBuilder) SetDefineConfig(key string, val interface{}) *Cu
return ccb
}

// CustomFunc must not block
type CustomFunc func(config *RootConfig) error

func (ccb *CustomConfigBuilder) AddCustomFunc(fc CustomFunc) *CustomConfigBuilder {
ccb.customConfig.Functions = append(ccb.customConfig.Functions, fc)
return ccb
}

func (ccb *CustomConfigBuilder) Build() *CustomConfig {
return ccb.customConfig
}
19 changes: 19 additions & 0 deletions config/custom_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,22 @@ func TestConfigUtils(t *testing.T) {
element := removeDuplicateElement([]string{"nacos", "nacos"})
assert.Equal(t, len(element), 1)
}

func TestCustomFunc(t *testing.T) {
t.Run("custom func", func(t *testing.T) {
customConfigBuilder := NewCustomConfigBuilder()
customConfigBuilder.SetDefineConfig("password", "encrypt")
customConfigBuilder.AddCustomFunc(func(rootConfig *RootConfig) error {
//decrypt the password
rootConfig.Custom.ConfigMap["password"] = "decrypt"
return nil
})
customConfig := customConfigBuilder.Build()
rootConfig.Custom = customConfig
err := customConfig.Init()
if err != nil {
return
}
assert.Equal(t, "decrypt", customConfig.GetDefineValue("password", ""))
})
}