base-golang/pkg/apollo/config.go
2024-07-31 16:49:14 +08:00

98 lines
2.1 KiB
Go

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
conf any
onChange func(event *storage.ChangeEvent)
onNewestChange func(*storage.FullChangeEvent)
}
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 GetApolloConfig(appId, secret string, config any, opt ...Option) error {
var err error
namespace := env.Active().Value() + ".yaml"
c := new(clientConfig)
c.conf = config
c.ac = &apolloConfig.AppConfig{
AppID: appId,
Cluster: "dev",
IP: "https://config.bvbej.com",
NamespaceName: namespace,
IsBackupConfig: false,
Secret: secret,
MustStart: true,
}
for _, option := range opt {
option(c)
}
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)
}
}