2025-02-08 18:57:05 +08:00
package config
import (
2025-02-14 11:46:37 +08:00
"context"
"fmt"
2025-02-08 18:57:05 +08:00
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
"github.com/zeromicro/go-zero/zrpc"
2025-02-14 11:46:37 +08:00
clientv3 "go.etcd.io/etcd/client/v3"
2025-02-08 18:57:05 +08:00
)
const (
TypeKey = "CONFIG_TYPE" // 配置文件类型
TypeEtcd = "etcd"
TypeEnv = "env"
2025-02-14 11:46:37 +08:00
Prefix = "/youtu/config/" // 配置文件前缀
2025-02-08 18:57:05 +08:00
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 ) {
2025-02-14 11:46:37 +08:00
err = viper . AddRemoteProvider ( "etcd3" , viper . GetString ( EtcdAddrKey ) , Prefix + serverName + ".rpc" )
fmt . Println ( Prefix + serverName + ".rpc" )
2025-02-08 18:57:05 +08:00
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
}
2025-02-14 11:46:37 +08:00
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
}