一、简介
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文件一致文章来源:https://www.toymoban.com/news/detail-791961.html
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"文章来源地址https://www.toymoban.com/news/detail-791961.html
var config Config
configPath := "config.toml"
if _, err := toml.DecodeFile(configPath, &config); err != nil {
fmt.Errorf("Error decoding TOML file: %v", err)
}
到了这里,关于【go语言】读取toml文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!