📖 3 min read (~ 700 words).

Keep comments through a round trip

The task: load a commented configuration file into a struct, and write it back without losing the comments.

The type and the file

type Config struct {
	Name  string `yaml:"name"`
	Ports []int  `yaml:"ports"`
	DB    DB     `yaml:"db"`
}

type DB struct {
	Host string `yaml:"host"`
	Port int    `yaml:"port"`
}

Full source: docs/examples/encoding/comments/example_test.go

const src = `# service settings
name: api   # the public name
# listening ports
ports:
  - 80   # http
  - 443
db:
  host: localhost  # dev only
  # default postgres port
  port: 5432
# trailing comment
`

Full source: docs/examples/encoding/comments/example_test.go

Read the comments while decoding

cm := codec.CommentMap{}

var c Config
if err := codec.Unmarshal([]byte(src), &c, codec.CommentToMap(cm)); err != nil {
	fmt.Println(err)

	return
}

Full source: docs/examples/encoding/comments/example_test.go

CommentToMap fills cm with every comment in the file, keyed by the path of the value it belongs to. Printed in path order:

$.db       Foot [" trailing comment"]
$.db.host  Line [" dev only"]
$.db.port  Head [" default postgres port"]
$.name     Head [" service settings"]
$.name     Line [" the public name"]
$.ports    Head [" listening ports"]
$.ports[0] Line [" http"]

Full source: docs/examples/encoding/comments/example_test.go

Each entry is a slice of *codec.Comment, so one path can hold a head and a line comment. A comment above the first key, # service settings, is the head of $.name. A comment after the last key, # trailing comment, is the foot of $.db, the last value at the top level.

Write them back

out, err := codec.Marshal(c, codec.WithComment(cm))
if err != nil {
	fmt.Println(err)

	return
}
fmt.Print(string(out))

Full source: docs/examples/encoding/comments/example_test.go

# service settings
name: api # the public name
# listening ports
ports:
- 80 # http
- 443
db:
  host: localhost # dev only
  # default postgres port
  port: 5432
# trailing comment

Full source: docs/examples/encoding/comments/example_test.go

All seven comments come back, each in its place. The layout is the encoder’s:

  • a line comment has one space before its #, where the file had two or three;
  • the ports entries move to column 0, the encoder’s default. Pass codec.IndentSequence(true) to indent them.

Into a map, the order moves

cm := codec.CommentMap{}

var m map[string]any
if err := codec.Unmarshal([]byte(src), &m, codec.CommentToMap(cm)); err != nil {
	fmt.Println(err)

	return
}

out, _ := codec.Marshal(m, codec.WithComment(cm))
fmt.Print(string(out))

Full source: docs/examples/encoding/comments/example_test.go

db:
  host: localhost # dev only
  # default postgres port
  port: 5432
# trailing comment
# service settings
name: api # the public name
# listening ports
ports:
- 80 # http
- 443

Full source: docs/examples/encoding/comments/example_test.go

The encoder writes a Go map’s keys sorted, so db comes first. Every comment follows its own path, and # trailing comment follows $.db to the middle of the file. Decode into a struct, or into an any with codec.UseOrderedMap, which gives a codec.MapSlice, to keep the file’s order.

Add a comment

// A comment's text is written after the "#" as it stands: put the space in.
cm := codec.CommentMap{
	"$.name": {codec.HeadComment(" managed by the ops team")},
	"$.db":   {codec.LineComment(" see the runbook")},
}

out, _ := codec.Marshal(Config{Name: "api", DB: DB{Host: "db", Port: 5432}}, codec.WithComment(cm))
fmt.Print(string(out))

Full source: docs/examples/encoding/comments/example_test.go

# managed by the ops team
name: api
ports: []
db: # see the runbook
  host: db
  port: 5432

Full source: docs/examples/encoding/comments/example_test.go

HeadComment, LineComment and FootComment build an entry with its position set. The text goes after the # as given, so put the space in.

Variations

  • Edit the file in place. A CommentMap keeps the comments, not the layout. To change one value and leave every other byte as it was, see Change one value, keep the file.
  • Paths are required. The map is keyed by the paths the parser records. parser.WithOmitNodePaths turns them off, and the map then comes back keyed by empty strings. See Comments.