This is a minimal example showing how to read, edit, and write YAML using Go structs while preserving comments, using the goccy/go-yaml
library.
package main
import (
"fmt"
"os"
"github.com/goccy/go-yaml"
)
type Config struct {
Name string `yaml:"name"`
Age int `yaml:"age"`
Active bool `yaml:"active"`
}
func main() {
data, _ := os.ReadFile("input.yaml")
// Define the target struct
var cfg Config
// Prepare a CommentMap to capture comments
comments := yaml.CommentMap{}
// Unmarshal with comment capture
err = yaml.UnmarshalWithOptions(data, &cfg, yaml.CommentToMap(comments))
if err != nil {
panic(err)
}
// Modify the struct
cfg.Age = 42
// Marshal back to YAML with preserved comments
output, err := yaml.MarshalWithOptions(cfg, yaml.WithComment(comments))
if err != nil {
panic(err)
}
fmt.Println(string(output))
}