Golang - 生成toml文件和读取toml文件

代码示例: 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值