有这样一种使用场景,Golang从文件或字符串中读取toml数据并解析,然后进行相应的修改,最后重新写回到文件中,由于一般的toml库不会去特别处理注释,重新生成的toml文件中所有原始的注释都会丢失,以 github.com/BurntSushi/toml 为例:

package main

import (
	"log"
	"os"

	"github.com/BurntSushi/toml"
)

func main() {

	tomlText := `
#comment for user
[user]
name = "Tom" # comment for name
age = 30 # comment for age
`
	var m map[string]interface{}
	if _, err := toml.Decode(tomlText, &m); err != nil {
		log.Fatal(err)
	}
	if err := toml.NewEncoder(os.Stdout).Encode(m); err != nil {
		log.Fatal(err)
	}
}

以上代码会输出:

[user]
  age = 30
  name = "Tom"
github.com/BurntSushi/tomlEncodeWithComments()github.com/GuanceCloud/toml
package main

import (
	"log"
	"os"

	"github.com/GuanceCloud/toml"
)

func main() {

	tomlText := `
#comment for user
[user]
name = "Tom" # comment for name
age = 30 # comment for age
`
	var m map[string]interface{}
	meta, err := toml.Decode(tomlText, &m)
	if err != nil {
		log.Fatal(err)
	}
	if err := toml.NewEncoder(os.Stdout).EncodeWithComments(m, meta); err != nil {
		log.Fatal(err)
	}
}

会输出:

#comment for user
[user]
  age = 30 # comment for age

  name = "Tom" # comment for name