您的位置:首页 > 编程语言 > Go语言

Go语言如何使用toml进行配置和解析

2018-02-06 16:57 387 查看
之前介绍过如何简单的读取key=value的配置解析方法:读取配置内容方法

今天来介绍一个项目中常用的toml解析方法

1.配置文件名 xxxx.toml

2.解析方式 toml.Decoder()

main.go

package  main

import (
"fmt"
"github.com/BurntSushi/toml"
)

//订制配置文件解析载体
type Config struct{
Database *Database
SQL *SQL
}

//订制Database块
type Database struct {
Driver    string
Username  string `toml:"us"` //表示该属性对应toml里的us
Password string
}
//订制SQL语句结构
type SQL struct{
Sql1 string `toml:"sql_1"`
Sql2 string `toml:"sql_2"`
Sql3 string `toml:"sql_3"`
Sql4 string `toml:"sql_4"`
}

var config *Config=new (Config)
func init(){
//读取配置文件
_, err := toml.DecodeFile("test.toml",config)
if err!=nil{
fmt.Println(err)
}
}
func main() {
fmt.Println(config)
fmt.Println(config.Database)
fmt.Println(config.SQL.Sql1)
}


test.toml

#This file as Config struct

#this block as Database struct
[Database]
driver="jdbc:mysql.jdbc.Driver"
us="ft"
password="123"

#this block as SQL struct
[SQL]
sql_1= "select * from user"
sql_2="updata user set name = 'exo'"
sql_3="delete * from user"
sql_4="Insert into user(id,name) values(5,'ft')"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go语言