《go 中支持配置文件注释的库推荐》
在使用配置文件时,保留注释非常重要。通常,viper 在更新配置后会丢失注释。对于这个问题,我们找到了一个有效的解决方案。
我们推荐使用 go-yaml 库。它提供了 yaml.node 结构,可以与 marshal 和 unmarshal 一起使用来保留注释信息。
以下是使用 go-yaml 库保留配置文件注释的示例代码:
import ( "log" "strings" "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) }
输出:
INPUT: block1: # the comment map: key1: a key2: b block2: hi: there RESULT: block1: # the comment map: key1: a key2: b block2: hi: there
通过使用 go-yaml 库,我们能够在配置文件中保留注释。
以上就是Go 配置文件如何保留注释?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号