加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang读取配置文件

发布时间:2020-12-16 09:26:40 所属栏目:大数据 来源:网络整理
导读:golang使用viper包解析配置文件 1 package main 2 3 import ( 4 " fmt " 5 6 " github.com/spf13/viper " 7 ) 8 9 var Conf = Config{} 10 11 type RemoteAddress struct { 12 TestAddr [] string `mapstructure: " test_addr " ` 13 ProductionAddr [] stri

golang使用viper包解析配置文件

 1 package main
 2 
 3 import (
 4     "fmt"
 5 
 6     "github.com/spf13/viper"
 7 )
 8 
 9 var Conf = &Config{}
10 
11 type RemoteAddress struct {
12     TestAddr       []string `mapstructure:"test_addr"`
13     ProductionAddr []string `mapstructure:"production_addr"`
14 }
15 
16 type HTTPConfig struct {
17     Address string `mapstructure:"address"`
18     Port    string `mapstructure:"port"`
19 }
20 
21 type RPCConfig struct {
22     Address string `mapstructure:"address"`
23     Port    string `mapstructure:"port"`
24 }
25 
26 type Server struct {
27     HTTP          HTTPConfig    `mapstructure:"http"`
28     RPC           RPCConfig     `mapstructure:"rpc"`
29     RemoteAddress RemoteAddress `mapstructure:"remote_address"`
30 }
31 
32 type Client struct {
33     HTTP HTTPConfig `mapstructure:"http"`
34     RPC  RPCConfig  `mapstructure:"rpc"`
35 }
36 
37 type Config struct {
38     Server Server `mapstructure:"server"`
39     Client Client `mapstructure:"client"`
40 }
41 
42 func main() {
43     c := &Config{}
44     filename := "./conf.yaml"
45 
46     viper.SetConfigType("yaml")
47     viper.SetConfigFile(filename)
48 
49     err := viper.ReadInConfig()
50     if err != nil {
51         fmt.Println("read config is failed err:",err)
52     }
53 
54     err = viper.Unmarshal(c)
55     if err != nil {
56         fmt.Println("unmarshal config is failed,err:",err)
57     }
58 
59     fmt.Println("------",*c)
60 }

配置文件

 1 server:
 2   http:
 3     address:
 4       "0.0.0.0"
 5     port:
 6       "9988"
 7   rpc:
 8     address:
 9       "0.0.0.0"
10     port:
11       "9989"
12 
13   log:
14     dir:
15       "./server.log"
16 
17   remote_address:
18     test_addr:
19       "10.25.88.11"
20     production_addr:
21       - "127.0.0.2"
22       - "127.0.0.3"
23       - "127.0.0.4"
24 
25 client:
26   http:
27     address:
28       "0.0.0.0"
29     port:
30       "9987"
31   rpc:
32     address:
33       "0.0.0.0"
34     port:
35       "9989"
36   log:
37     dir:
38       "./client.log"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读