Golang 读取 TOML 配置文件:读取 IP 地址列表
Golang 读取 TOML 配置文件:读取 IP 地址列表
本文介绍使用 Golang 读取 TOML 配置文件,并从中获取 IP 地址列表。
示例 TOML 配置文件(config.toml):
enna_plat = [
'192.168.1.164',
'192.168.1.165'
]
Golang 代码(config.go):
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
type Config struct {
EnnaPlat []string `toml:"enna_plat"
}
func main() {
var conf Config
if _, err := toml.DecodeFile("config.toml", &conf); err != nil {
fmt.Println(err)
return
}
fmt.Println(conf.EnnaPlat)
}
代码说明:
- 定义 Config 结构体: 包含一个切片
EnnaPlat,用于存储配置文件中的 IP 地址列表。 - 使用
toml.DecodeFile解析配置文件: 将配置文件解析到 Config 结构体中。 - 打印 IP 地址列表: 使用
fmt.Println打印conf.EnnaPlat的内容。
安装第三方库:
go get github.com/BurntSushi/toml
运行代码:
- 将
config.go和config.toml文件保存到同一目录下。 - 运行
go run config.go命令。
结果:
[192.168.1.164 192.168.1.165]
注意:
- 请确保配置文件
config.toml中的内容与示例一致。 - 可以根据实际需求修改配置文件内容和 Golang 代码。
原文地址: https://www.cveoy.top/t/topic/lOGW 著作权归作者所有。请勿转载和采集!