2.4 KiB
2.4 KiB
TOML 简介
TOML(Tom's Obvious, Minimal Language)是一种配置文件格式,旨在易于阅读和编写。它的语法类似于INI文件,但更强大和灵活。
基本语法
-
键值对:
key = "value"
-
字符串:
string = "Hello, World!" multi_line_string = """ This is a multi-line string. nihao """
-
数字:
integer = 42 float = 3.14
-
布尔值:
boolean = true
-
数组:
array = [1, 2, 3]
-
表(嵌套结构):
[table] key = "value"
-
数组表:
[[array_table]] name = "Alice" [[array_table]] name = "Bob"
使用 Go 的 Viper 解析 TOML
在go中,有很多的库可以解析Toml,在这里我推荐使用Viper来进行处理。Viper 是一个强大的 Go 库,用于处理配置文件,支持多种格式,不仅仅是TOML。
示例代码
-
创建 TOML 文件(
config.toml
):app_name = "Class" port = 8080 [database] host = "localhost" port = 3306 user = "yzk_study" password = "yzk722923"
-
使用 Viper 解析 TOML:
package main import ( "fmt" "github.com/spf13/viper" ) func main() { // 设置配置文件名和路径 viper.SetConfigName("config") // 文件名(不带扩展名) viper.SetConfigType("toml") // 文件类型 viper.AddConfigPath(".") // 查找路径 // 读取配置文件 if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } // 获取配置值 appName := viper.GetString("app_name") port := viper.GetInt("port") dbHost := viper.GetString("database.host") dbPort := viper.GetInt("database.port") fmt.Printf("App Name: %s\n", appName) fmt.Printf("Port: %d\n", port) fmt.Printf("Database Host: %s\n", dbHost) fmt.Printf("Database Port: %d\n", dbPort) }
运行结果
App Name: MyApp
Port: 8080
Database Host: localhost
Database Port: 5432
总结
- TOML 是一种易于阅读和编写的配置文件格式。
- Viper 是一个强大的 Go 库,支持多种配置文件格式,包括 TOML。
- 通过 Viper,可以轻松读取和解析 TOML 文件中的配置项。