golang读取配置文件

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"

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...