求推荐一个golang下使用配置文件的库,要求能保留注释?

用了viper,但更新配置后注释没了,这太要命了,找了一圈没发现合适的,配置文件可以是json5yaml,别的类型不能储存复杂数据

谢谢

阅读 1.1k
1 个回答

我也找过,目前只发现一个办法。像是 go-yaml 这个库提供了 yaml.Node 结构,Marshal/Unmarshal 到这个结构可以保留注释信息。

package main

import (
    "log"
    "strings"

    yaml "gopkg.in/yaml.v3"
)

func main() {
    var node yaml.Node

    data := []byte(strings.TrimSpace(`
block1:
    # the comment
    map:
        key1: a
        key2: b
    
block2:
    hi: there

`))

    log.Printf("INPUT:\n %s", data)

    if err := yaml.Unmarshal(data, &node); err != nil {
        log.Fatalf("Unmarshalling failed %s", err)
    }

    results, err := yaml.Marshal(node.Content[0])
    if err != nil {
        log.Fatalf("Marshalling failed %s", err)
    }

    log.Printf("RESULT:\n %s", results)
}

输出

2009/11/10 23:00:00 INPUT:
 block1:
    # the comment
    map:
        key1: a
        key2: b
    
block2:
    hi: there
2009/11/10 23:00:00 RESULT:
 block1:
    # the comment
    map:
        key1: a
        key2: b
block2:
    hi: there
推荐问题