TeamClass_MD/Go入门速成/Day2/序篇 Toml文件.md

115 lines
2.4 KiB
Markdown
Raw Normal View History

2025-03-19 21:50:20 +08:00
### TOML 简介
TOMLTom's Obvious, Minimal Language是一种配置文件格式旨在易于阅读和编写。它的语法类似于INI文件但更强大和灵活。
#### 基本语法
1. **键值对**
```toml
key = "value"
```
2. **字符串**
```toml
string = "Hello, World!"
multi_line_string = """
This is a
multi-line string.
"""
```
3. **数字**
```toml
integer = 42
float = 3.14
```
4. **布尔值**
```toml
boolean = true
```
5. **数组**
```toml
array = [1, 2, 3]
```
6. **表(嵌套结构)**
```toml
[table]
key = "value"
```
7. **数组表**
```toml
[[array_table]]
name = "Alice"
[[array_table]]
name = "Bob"
```
### 使用 Go 的 Viper 解析 TOML
在go中有很多的库可以解析Toml,在这里我推荐使用Viper来进行处理。Viper 是一个强大的 Go 库用于处理配置文件支持多种格式不仅仅是TOML。
#### 示例代码
1. **创建 TOML 文件**`config.toml`
```toml
app_name = "Class"
port = 8080
[database]
host = "localhost"
port = 3306
user = "yzk_study"
password = "yzk722923"
```
2. **使用 Viper 解析 TOML**
```go
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)
}
```
#### 运行结果
```bash
App Name: MyApp
Port: 8080
Database Host: localhost
Database Port: 5432
```
### 总结
- **TOML** 是一种易于阅读和编写的配置文件格式。
- **Viper** 是一个强大的 Go 库,支持多种配置文件格式,包括 TOML。
- 通过 Viper可以轻松读取和解析 TOML 文件中的配置项。