package apollo import ( "encoding/json" "service/bizcommon/util" "service/library/configcenter" "service/library/logger" "github.com/apolloconfig/agollo/v4" "github.com/apolloconfig/agollo/v4/env/config" ) var defaultApolloClient agollo.Client func Init(cfg *configcenter.ApolloConfig) (err error) { clientCfg := &config.AppConfig{ AppID: cfg.AppID, Cluster: cfg.Cluster, IP: cfg.IP, NamespaceName: cfg.NamespaceName, IsBackupConfig: cfg.IsBackUpConfig, Secret: cfg.Secret, SyncServerTimeout: cfg.SyncServerTimeout, } agollo.SetLogger(logger.Global) defaultApolloClient, err = agollo.StartWithConfig(func() (*config.AppConfig, error) { return clientCfg, nil }) if err != nil { logger.Error("NewApolloClient fail, cfg: %v, err: %v", util.ToJson(clientCfg), err) return } return } type ApolloOptions struct { Namespace *string DefaultValue *string DefaultIntValue *int } func mergeApolloOptions(opts ...*ApolloOptions) *ApolloOptions { ao := ApolloOpts() for _, opt := range opts { if opt == nil { continue } if opt.Namespace != nil { ao.Namespace = opt.Namespace } if opt.DefaultValue != nil { ao.DefaultValue = opt.DefaultValue } if opt.DefaultIntValue != nil { ao.DefaultIntValue = opt.DefaultIntValue } } return ao } func ApolloOpts() *ApolloOptions { return &ApolloOptions{} } func (ao *ApolloOptions) SetNamespace(ns string) *ApolloOptions { ao.Namespace = &ns return ao } func (ao *ApolloOptions) SetDefaultValue(value string) *ApolloOptions { ao.DefaultValue = &value return ao } func (ao *ApolloOptions) GetNamespace() string { if ao != nil && ao.Namespace != nil { return *ao.Namespace } return "" } func (ao *ApolloOptions) GetDefaultValue() string { if ao != nil && ao.DefaultValue != nil { return *ao.DefaultValue } return "" } func (ao *ApolloOptions) GetDefaultIntValue() int { if ao != nil && ao.DefaultIntValue != nil { return *ao.DefaultIntValue } return 0 } func GetJson(key string, v interface{}, opts ...*ApolloOptions) (err error) { opt := mergeApolloOptions(opts...) var value string if opt.GetNamespace() != "" { value = defaultApolloClient.GetConfig(opt.GetNamespace()).GetStringValue(key, opt.GetDefaultValue()) } else { value = defaultApolloClient.GetStringValue(key, opt.GetDefaultValue()) } if value != "" { return json.Unmarshal([]byte(value), v) } return } func GetStringValue(key string, opts ...*ApolloOptions) (value string, err error) { opt := mergeApolloOptions(opts...) if opt.GetNamespace() != "" { value = defaultApolloClient.GetConfig(opt.GetNamespace()).GetStringValue(key, opt.GetDefaultValue()) } else { value = defaultApolloClient.GetStringValue(key, opt.GetDefaultValue()) } return } func GetIntValue(key string, opts ...*ApolloOptions) (value int, err error) { opt := mergeApolloOptions(opts...) if opt.GetNamespace() != "" { value = defaultApolloClient.GetConfig(opt.GetNamespace()).GetIntValue(key, opt.GetDefaultIntValue()) } else { value = defaultApolloClient.GetIntValue(key, opt.GetDefaultIntValue()) } return }