package apollo import ( "fmt" "gitea.bvbej.com/bvbej/base-golang/pkg/env" "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 onChange func(event *storage.ChangeEvent) onNewestChange func(*storage.FullChangeEvent) conf any cluster string addr string } type Option func(*clientConfig) func WithOnChangeEvent(event func(event *storage.ChangeEvent)) Option { return func(conf *clientConfig) { conf.onChange = event } } func WithOnNewestChangeEvent(event func(event *storage.FullChangeEvent)) Option { return func(conf *clientConfig) { conf.onNewestChange = event } } func WithCluster(cluster string) Option { return func(conf *clientConfig) { conf.cluster = cluster } } func WithAddr(addr string) Option { return func(conf *clientConfig) { conf.addr = addr } } func GetApolloConfig(appId, secret string, config any, opt ...Option) error { var err error c := &clientConfig{ cluster: "dev", addr: "https://config.bvbej.com", conf: config, } for _, option := range opt { option(c) } namespace := env.Active().Value() + ".yaml" c.ac = &apolloConfig.AppConfig{ AppID: appId, Cluster: c.cluster, IP: c.addr, NamespaceName: namespace, IsBackupConfig: false, Secret: secret, MustStart: true, } agollo.SetLogger(&log.DefaultLogger{}) c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) { return c.ac, nil }) if err != nil { return fmt.Errorf("get config error:[%s]", err) } c.client.AddChangeListener(c) err = c.serialization() if err != nil { return fmt.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() if c.onChange != nil { c.onChange(event) } } func (c *clientConfig) OnNewestChange(event *storage.FullChangeEvent) { if c.onNewestChange != nil { c.onNewestChange(event) } }