代码示例:
package main
import (
"fmt"
"github.com/pelletier/go-toml"
"os"
"path"
)
func CreateToml(tomlPath string) {
tree, err := toml.Load("")
if err != nil {
fmt.Println("Error while creating empty Toml tree:", err)
return
}
subtree, err := toml.Load("")
subtree.Set("key1", "value1 - %s")
subtree.Set("key2", "42")
subtree.Set("key3", true)
tree.Set("report_config", subtree)
file, err := os.Create(tomlPath)
if err != nil {
fmt.Println("Error while creating Toml file:", err)
return
}
defer file.Close()
_, err = tree.WriteTo(file)
if err != nil {
fmt.Println("Error while writing to Toml file:", err)
return
}
fmt.Println("Toml file created successfully.")
}
func ReadToml(path string) {
tree, err := toml.LoadFile(path)
if err != nil {
fmt.Println("Error while loading Toml file:", err)
return
}
value := tree.Get("report_config.key1").(string)
fmt.Println("value: ", value)
// test
res := fmt.Sprintf(value, "name")
fmt.Println("res: ", res)
}
func main() {
currPath, _ := os.Getwd()
tomlPath := path.Join(currPath, "test/config_FLAG/chart_config.toml")
fmt.Println("tomlPath: ", tomlPath)
// Golang生成写入toml文件 - write
CreateToml(tomlPath)
// Golang读取toml文件 - read
ReadToml(tomlPath)
}
toml文件示例:
[report_config]
key1 = "value1 - %s"
key2 = "42"
key3 = true