Toml文件

在项目根目录下新建一个toml文件并命名为ta.toml,写入如下内容:

os="windows"
version="10"
[server]
addr="192.168.1.1"
port="80"
http="https"
route="/test/indes"

第三方库安装

go get github.com/pelletier/go-toml

读取配置文件内容

1、读取一级key-value的值

package main

import (
	"fmt"
	"github.com/pelletier/go-toml"
)

func main()  {
	config, _ := toml.LoadFile("./ta.toml") //加载toml文件
	key:= config.Get("os").(string) //读取key对应的值.括号为指定数据类型,也可以忽略
	fmt.Println(key)
}

2、读取二级key-value的值

package main

import (
	"fmt"
	"github.com/pelletier/go-toml"
)

func main()  {
	config, _ := toml.LoadFile("./ta.toml") //加载toml文件
	key:= config.Get("server.addr") //读取key对应的值.括号为指定数据类型
	fmt.Println(key)
}

注:读取指定数据的时候可以指定数据类型,也可以让系统自动推导,区别在于指定类型时可以在读取过程中较验数据类型是否正确,如果不确定数据类型时,可以不指定。

扩展阅读

toml格式规范:

toml各语言驱动:

toml转json工具: