BurntSushi/toml

GitHub: BurntSushi/toml

Go 语言的 TOML 配置解析与编码库,通过反射机制实现 TOML 文件与 Go 结构体之间的自动转换,并提供独立的文件验证命令行工具。

Stars: 4985 | Forks: 556

TOML 代表 Tom's Obvious, Minimal Language。这个 Go 包提供了类似于 Go 标准库 `json` 和 `xml` 包的反射接口。 兼容 TOML 版本 [v1.1.0](https://toml.io/en/v1.1.0)。 文档:https://pkg.go.dev/github.com/BurntSushi/toml 查看 [发布页面](https://github.com/BurntSushi/toml/releases) 获取更新日志;此信息也包含在 git 标签注释中(例如 `git show v0.4.0`)。 此库需要 Go 1.19 或更高版本;使用以下命令将其添加到您的 go.mod 中: ``` % go get github.com/BurntSushi/toml@latest ``` 它还附带了一个 TOML 验证器 CLI 工具: ``` % go install github.com/BurntSushi/toml/cmd/tomlv@latest % tomlv some-toml-file.toml ``` ### 示例 对于最简单的示例,请将某个 TOML 文件视为单纯的键和 值的列表: ``` Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` 可以使用以下代码进行解码: ``` type Config struct { Age int Cats []string Pi float64 Perfection []int DOB time.Time } var conf Config _, err := toml.Decode(tomlData, &conf) ``` 如果您的 struct 字段名不能直接映射到 TOML 键值,您也可以使用 struct tag: ``` some_key_NAME = "wat" ``` ``` type TOML struct { ObscureKey string `toml:"some_key_NAME"` } ``` 请注意,与其他解码器一样,在编码和解码时**仅考虑导出的字段**;私有字段会被静默忽略。 ### 使用 `Marshaler` 和 `encoding.TextUnmarshaler` 接口 以下是一个自动解析 `mail.Address` 值的示例: ``` contacts = [ "Donald Duck ", "Scrooge McDuck ", ] ``` 可以使用以下代码进行解码: ``` // Create address type which satisfies the encoding.TextUnmarshaler interface. type address struct { *mail.Address } func (a *address) UnmarshalText(text []byte) error { var err error a.Address, err = mail.ParseAddress(string(text)) return err } // Decode it. func decode() { blob := ` contacts = [ "Donald Duck ", "Scrooge McDuck ", ] ` var contacts struct { Contacts []address } _, err := toml.Decode(blob, &contacts) if err != nil { log.Fatal(err) } for _, c := range contacts.Contacts { fmt.Printf("%#v\n", c.Address) } // Output: // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"} // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"} } ``` 为了专门针对 TOML,您可以以类似的方式实现 `UnmarshalTOML` 接口。 ### 更复杂的用法 有关更复杂的示例,请参阅 [`_example/`](/_example) 目录。
标签:EVTX分析, Python安全, 日志审计