BurntSushi / toml

TOML parser for Golang with reflection.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to rewrite toml file

xiaozuo7 opened this issue · comments

Hello, I want to parse the toml file, and then overwrite the original toml file after modifying some values, but I have not found a method similar to Marshal(), and the encode method needs to create a NewEncoder() object first, which I think is very strange.

The following is the code I implemented using yaml. Please give me some suggestions on how to write toml.

package main

import (
	"log"
	"os"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Host string `yaml:"host"`
}

func main() {
	confPath := "conf.yaml"
	file, err := os.ReadFile(confPath)
	if err != nil {
		log.Fatal(err)
	}
	config := new(Config)
	err = yaml.Unmarshal(file, config)
	if err != nil {
		log.Fatal(err)
	}

	config.Host = "8.8.8.8" // modify host
	modifyConf, err := yaml.Marshal(config)
	if err != nil {
		log.Fatal(err)
	}
	err = os.WriteFile(confPath, modifyConf, 0644)
	if err != nil {
		log.Fatal(err)
	}

}

conf.yaml

host: 127.0.0.1

After running the code, the original yaml file host should be modified

It seems that there is no problem with this implementation

package main

import (
	"bytes"
	"log"
	"os"

	"github.com/BurntSushi/toml"
)

type Config struct {
	Host string `yaml:"host"`
}

func main() {
	confPath := "conf.toml"
	config := new(Config)
	_, err := toml.DecodeFile(confPath, config)
	if err != nil {
		log.Fatal(err)
	}

	config.Host = "8.8.8.8" // modify host
	var modifyConf bytes.Buffer
	err = toml.NewEncoder(&modifyConf).Encode(config)
	if err != nil {
		log.Fatal(err)
	}
	err = os.WriteFile(confPath, modifyConf.Bytes(), 0644)
	if err != nil {
		log.Fatal(err)
	}

}

Maybe this can be added to the _example/