YAML marshaling with comment support via struct tags, built on top of gopkg.in/yaml.v3, making generated config files self-documenting and easy-readable without any post-processing.
go get github.com/denwwer/yamlcAdd a comment struct tag to annotate fields. By default the comment is placed above the key (head comment). Prefix with > to place it inline (line comment).
type Config struct {
Port int `yaml:"port,omitempty" comment:"Default port"`
Log Log `yaml:"log" comment:"Defines the configuration for logging"`
DevMode bool `yaml:"dev_mode"`
Versions *Versions `yaml:"versions" comment:"> Use version 10"`
Password string `yaml:"-" comment:"App password"`
Keys map[string]string `yaml:"keys" comment:"Custom keys"`
}
type Log struct {
Level string `yaml:"level" comment:"Log level: error | info | debug (default: info)"`
Format string `yaml:"format" comment:"> text | json"`
}
type Versions []stringf, err := os.Create("config.yaml")
if err != nil {
return err
}
defer f.Close()
enc := yamlc.NewEncoder(yaml.NewEncoder(f))
err = enc.Encode(cfg)| Tag value | Result |
|---|---|
"Some text" |
Head comment (above the key) |
"> Some text" |
Line comment (next to the key) |
# Defines the configuration for logging
log:
# Log level: error | info | debug (default: info)
level: ""
format: text # text | json
dev_mode: false
versions: # Use version 10
- v1
- v10
# Custom keys
keys:
"1": k-1
"2": k-2