| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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)
- }
|