Skip to content

Instantly share code, notes, and snippets.

@Dentrax
Last active May 27, 2025 14:18
Show Gist options
  • Save Dentrax/3481e2fb4eda4f5fac0371a0ccd1b02f to your computer and use it in GitHub Desktop.
Save Dentrax/3481e2fb4eda4f5fac0371a0ccd1b02f to your computer and use it in GitHub Desktop.
Go: Preserving YAML comments when (un)marshaling

YAML Comment Preservation in Go (Using Structs)

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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment