Golang中Toml实现配置文件转对象

Posted by Wang Gang on 2019-08-21

配置信息转化成对象信息

当我们相对某一个固定变量进行赋值的情况,比如mysql的配置信息,redis的配置信息,这些比较固定的信息,可以通过编写配置信息来实现对信息的配置

配置信息:test.toml

1
2
3
4
5
6
7
8
9
10
11
12
addr="127.0.0.1:6389"
#log_path: /Users/flike/src
#日志级别
log_level="debug"

[storage_db]
mysql_host="127.0.0.1"
mysql_port=3306
db_name="redis"
user="root"
password="root123"
max_idle_conns=64

函数位置 main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
"io/ioutil"

"github.com/BurntSushi/toml"
)

type Config struct {
Addr string `toml:"addr"`
LogPath string `toml:"log_path"`
LogLevel string `toml:"log_level"`
DatabaseConfig *DBConfig `toml:"storage_db"`
}

type DBConfig struct {
Host string `toml:"mysql_host"`
Port int `toml:"mysql_port"`
User string `toml:"user"`
Password string `toml:"password"`
DBName string `toml:"db_name"`
MaxIdleConns int `toml:"max_idle_conns"`
}

func main(){
var configFile *string = flag.String("config", "test.toml", "idgo config file")
if len(*configFile) == 0 {
fmt.Println("must use a config file")
return
}

cfg, err := config.ParseConfigFile(*configFile)
if err != nil {
fmt.Printf("parse config file error:%v\n", err.Error())
return
}
}

func ParseConfigFile(fileName string) (*Config, error) {
var cfg Config

data, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}

_, err = toml.Decode(string(data), &cfg)
if err != nil {
return nil, err
}
return &cfg, nil
}