diff --git a/config/config_loader.go b/config/config_loader.go index 8b47ceb1c9..44c2abdd54 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -43,11 +43,16 @@ var ( func Load(opts ...LoaderConfOption) error { // conf conf := NewLoaderConf(opts...) - koan := GetConfigResolver(conf) - if err := koan.UnmarshalWithConf(rootConfig.Prefix(), - rootConfig, koanf.UnmarshalConf{Tag: "yaml"}); err != nil { - return err + if conf.rc == nil { + koan := GetConfigResolver(conf) + if err := koan.UnmarshalWithConf(rootConfig.Prefix(), + rootConfig, koanf.UnmarshalConf{Tag: "yaml"}); err != nil { + return err + } + } else { + rootConfig = conf.rc } + if err := rootConfig.Init(); err != nil { return err } diff --git a/config/config_loader_options.go b/config/config_loader_options.go index 598a478fd8..4994103298 100644 --- a/config/config_loader_options.go +++ b/config/config_loader_options.go @@ -44,6 +44,8 @@ type loaderConf struct { delim string // config bytes bytes []byte + // user provide rootConfig built by config api + rc *RootConfig } func NewLoaderConf(opts ...LoaderConfOption) *loaderConf { @@ -60,6 +62,9 @@ func NewLoaderConf(opts ...LoaderConfOption) *loaderConf { for _, opt := range opts { opt.apply(conf) } + if conf.rc != nil { + return conf + } if len(conf.bytes) <= 0 { bytes, err := ioutil.ReadFile(conf.path) if err != nil { @@ -105,6 +110,12 @@ func WithPath(path string) LoaderConfOption { }) } +func WithRootConfig(rc *RootConfig) LoaderConfOption { + return loaderConfigFunc(func(conf *loaderConf) { + conf.rc = rc + }) +} + func WithDelim(delim string) LoaderConfOption { return loaderConfigFunc(func(conf *loaderConf) { conf.delim = delim diff --git a/config/config_loader_options_test.go b/config/config_loader_options_test.go index 7704d52997..8943cc3ace 100644 --- a/config/config_loader_options_test.go +++ b/config/config_loader_options_test.go @@ -38,3 +38,9 @@ func TestFileGenre(t *testing.T) { conf := NewLoaderConf(WithPath("../config/testdata/config/properties/application.properties")) assert.Equal(t, conf.genre, "properties") } + +func TestRootConfig(t *testing.T) { + rc := NewRootConfigBuilder().SetApplication(NewApplicationConfigBuilder().SetName("test-app").Build()).Build() + conf := NewLoaderConf(WithRootConfig(rc)) + assert.Equal(t, conf.rc.Application.Name, "test-app") +} diff --git a/config/root_config.go b/config/root_config.go index 114d44fc9d..6841207686 100644 --- a/config/root_config.go +++ b/config/root_config.go @@ -131,6 +131,8 @@ func registerPOJO() { hessian.RegisterPOJO(&common.URL{}) } +// Init is to start dubbo-go framework, load local configuration, or read configuration from config-center if necessary. +// It's deprecated for user to call rootConfig.Init() manually, try config.Load(config.WithRootConfig(rootConfig)) instead. func (rc *RootConfig) Init() error { registerPOJO() if err := rc.Logger.Init(); err != nil { // init default logger