package apollo import ( "git.bvbej.com/bvbej/base-golang/pkg/env" "git.bvbej.com/bvbej/base-golang/pkg/errors" "github.com/apolloconfig/agollo/v4" "github.com/apolloconfig/agollo/v4/component/log" apolloConfig "github.com/apolloconfig/agollo/v4/env/config" "github.com/apolloconfig/agollo/v4/storage" "github.com/spf13/viper" ) type clientConfig struct { client agollo.Client ac *apolloConfig.AppConfig conf any change func(event *storage.ChangeEvent) } func GetApolloConfig(appId, secret string, config any, change func(event *storage.ChangeEvent)) error { var err error namespace := env.Active().Value() + ".yaml" c := new(clientConfig) c.conf = config c.change = change c.ac = &apolloConfig.AppConfig{ AppID: appId, Cluster: "dev", IP: "https://config.bvbej.com", NamespaceName: namespace, IsBackupConfig: true, Secret: secret, } agollo.SetLogger(&log.DefaultLogger{}) c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) { return c.ac, nil }) if err != nil { return errors.Errorf("get config error:[%s]", err) } c.client.AddChangeListener(c) err = c.serialization() if err != nil { return errors.Errorf("unmarshal config error:[%s]", err) } return nil } func (c *clientConfig) serialization() error { parser := viper.New() parser.SetConfigType("yaml") c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool { parser.Set(key.(string), value) return true }) return parser.Unmarshal(c.conf) } func (c *clientConfig) OnChange(event *storage.ChangeEvent) { _ = c.serialization() c.change(event) } func (c *clientConfig) OnNewestChange(*storage.FullChangeEvent) { // }