【go语言】读取toml文件

一、简介

TOML,全称为Tom's Obvious, Minimal Language,是一种易读的配置文件格式,旨在成为一个极简的数据序列化语言。TOML的设计原则之一是保持简洁性,易读性,同时提供足够的灵活性以满足各种应用场景。

TOML文件由多个表(table)组成,每个表包含一组键值对。键值对由键名、等号(或冒号),以及对应的值组成。TOML支持嵌套表,可以构建层次结构,使得配置文件更加结构化。

二、用法

github官方地址
GitHub - BurntSushi/toml: TOML parser for Golang with reflection.

# 一个包含各种数据类型的 TOML 示例

StringValue = "Hello, World!"

MultilineString = """
This is a
multi-line
string.
"""

IntegerValue = 42

FloatValue = 3.14

BooleanValue = true

ArrayValues = [1, 2, 3]

[[Table]]
NestedString = "Nested String 1"
NestedInteger = 123

[[Table]]
NestedString = "Nested String 2"
NestedInteger = 456
[[Table.NnTables]]
NnString = "NnTable String 2"
NnInteger = 456
[[Table.NnTables]]
NnString = "NnTable String 2"
NnInteger = 456

[[Table]]
NestedString = "Nested String 3"
NestedInteger = 789
[[Table.NnTables]]
NnString = "NnTable String 1"
NnInteger = 789

[Maps]
[Maps.Map1]
NestedString = "Map Nested String 1"
NestedInteger = 111

[Maps.Map2]
NestedString = "Map Nested String 2"
NestedInteger = 222

DatetimeValue = 2022-01-11T12:34:56Z


对应的go文件:注意命名大写且要和toml文件一致

type Config struct {
	StringValue     string
	MultilineString string
	IntegerValue    int
	FloatValue      float64
	BooleanValue    bool
	ArrayValues     []int
	Table           []NestedTable
	Maps            map[string]NestedTable
	DatetimeValue   time.Time
}

type NestedTable struct {
	NestedString  string
	NestedInteger int
	NnTables      []NnTable
}
type NnTable struct {
	NnString  string
	NnInteger int
}

 解析:导包 "github.com/BurntSushi/toml"

var config Config
	configPath := "config.toml"
	if _, err := toml.DecodeFile(configPath, &config); err != nil {
		fmt.Errorf("Error decoding TOML file: %v", err)
	}

你可能感兴趣的:(go,golang,开发语言,后端)