package main import ( "bytes" "context" "fmt" "github.com/go-kit/kit/sd/etcdv3" "github.com/spf13/viper" "time" ) type ( Config struct { App App `mapstructure:"app"` Mysql Mysql `mapstructure:"mysql"` Redis Redis `mapstructure:"redis"` Etcd Etcd `mapstructure:"etcd"` } App struct { ServerName string `mapstructure:"name"` Version string `mapstructure:"version"` LogLevel string `mapstructure:"log_level"` LogFormat string `mapstructure:"log_format"` Addr string `mapstructure:"addr"` Env string `mapstructure:"env"` RouterPrefix string `mapstructure:"router_prefix"` SignatureAuth bool `mapstructure:"signature_auth"` DefaultKeyPassword string `mapstructure:"default_key_password"` PrometheusAddr string `mapstructure:"prometheus_addr"` } Mysql struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` DB string `mapstructure:"db"` Username string `mapstructure:"username"` Password string `mapstructure:"password"` } Redis struct { Host string `mapstructure:"host"` Password string `mapstructure:"password"` DB int64 `mapstructure:"db"` } Etcd struct { Host string `mapstructure:"host"` Prefix string `mapstructure:"prefix"` Username string `mapstructure:"username"` Password string `mapstructure:"password"` } ) func InitEtcdClient(a string,b string,c string) etcdv3.Client{ //etcd连接参数 option := etcdv3.ClientOptions{ DialTimeout: time.Second * 3, DialKeepAlive: time.Second * 3, Username: b, Password: c, } //创建连接 client, err := etcdv3.NewClient(context.Background(), []string{a}, option) if err != nil { panic(err) } return client } func readConfig(data []byte) (*Config, error) { v := viper.New() v.SetConfigType("toml") reader := bytes.NewReader(data) err := v.ReadConfig(reader) if err != nil { return nil, err } cfg := &Config{} if err := v.Unmarshal(cfg); err != nil { return nil, err } return cfg, nil } func main(){ conn := InitEtcdClient("192.168.150.41:2379", "root", "JmZMbqQ1nc") resp, err := conn.GetEntries("/openapi/config") if err != nil { fmt.Println("Error: Get Config Data Error: ", err) return } fmt.Println([]byte(resp[0])) fmt.Println(resp[0]) resp2, err := conn.GetEntries("/test/config") if err != nil { fmt.Println("Error: Get Config Data Error: ", err) return } fmt.Println([]byte(resp2[0])) fmt.Println(resp2[0]) config, err := readConfig([]byte(resp2[0])) if err != nil { fmt.Println("Error: Get Config Data Error: ", err) return } fmt.Println(config) }