youtu_grpc/pkg/config/get_config.go
xiabin 207a6bbb95
All checks were successful
/ build-services (app/ranking/Dockerfile, ranking, ranking) (push) Successful in 39s
/ build-services (app/user/Dockerfile, user, user) (push) Successful in 39s
/ start-services (push) Successful in 4s
/ build-services (app/auth/Dockerfile, auth, auth) (push) Successful in 40s
/ build-services (app/ecpm/Dockerfile, ecpm, ecpm) (push) Successful in 37s
update
2025-02-14 11:58:28 +08:00

72 lines
1.6 KiB
Go

package config
import (
"context"
"fmt"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
"github.com/zeromicro/go-zero/zrpc"
clientv3 "go.etcd.io/etcd/client/v3"
)
const (
TypeKey = "CONFIG_TYPE" // 配置文件类型
TypeEtcd = "etcd"
TypeEnv = "env"
Prefix = "/youtu/config/" // 配置文件前缀
EtcdAddrKey = "ETCD_ADDR"
)
type Redis struct {
Host string `json:"host"`
Password string `json:"password"`
}
type AppAccount struct {
AppId string `json:"appId"`
Secret string `json:"secret"`
Type string `json:"type"`
}
type Config struct {
RpcServerConf zrpc.RpcServerConf
Mode string
Mysql string
Redis []Redis
}
func init() {
viper.SetDefault(EtcdAddrKey, "192.168.0.47:2379")
viper.SetDefault(TypeKey, TypeEtcd)
}
func GetConfig(c *Config, serverName string) (err error) {
err = viper.AddRemoteProvider("etcd3", viper.GetString(EtcdAddrKey), Prefix+serverName+".rpc")
fmt.Println(Prefix + serverName + ".rpc")
if err != nil {
return
}
viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
err = viper.ReadRemoteConfig()
if err != nil {
return
}
err = viper.Unmarshal(&c)
if err != nil {
return
}
c.RpcServerConf.Name = serverName + ".rpc"
c.RpcServerConf.ServiceConf.Mode = c.Mode
return
}
func SetConfig(b, serverName string) (err error) {
etcdCli, err := clientv3.NewFromURL(viper.GetString(EtcdAddrKey))
if err != nil {
return
}
_, err = etcdCli.Put(context.Background(), Prefix+serverName+".rpc", b)
return
}