About the YAML to Go Converter
Almost every Go service reads a YAML config, and almost every one of them starts with a hand written struct that drifts out of step with the file it is meant to describe. Pasting the config here regenerates that struct in a second, which makes it cheap to keep the two in agreement whenever the file gains a section.
Both json and yaml tags are written by default. That combination suits services that read a YAML file at boot and expose the same settings over an HTTP endpoint, and it is harmless if you only ever use one of them. Field names follow Go conventions with initialisms capitalised, so a key named id becomes ID, and the columns are padded so the output already matches what gofmt would produce.
Type inference follows the YAML spec rather than guessing from text. An unquoted false is a boolean, 6.2 is a float64, a quoted number stays a string, and a nested mapping becomes its own struct named after the key. Lists of mappings become slices of a singularised type, so a vehicles list yields []Vehicle. Turn on pointer fields when you need to distinguish an omitted section from one that was present but empty, which is the usual reason a config default silently fails to apply. If your input is JSON, JSON to Go does the same job.
How to use
- Paste the YAML config file you want to load in Go.
- Name the root struct, for example
ConfigorFleetSettings. - Keep both json and yaml tags unless you know only one serialiser will ever see the struct.
- Copy the structs into your project and unmarshal the file into the root type.
Common questions
- Which YAML library do these tags suit?
- The yaml tags follow the convention used by gopkg.in/yaml.v3 and sigs.k8s.io/yaml, both of which read lower case keys by default.
- Why is a quoted number a string?
- YAML treats a quoted value as text. That is deliberate for things like phone numbers and version strings, and the generated type respects it.
- Are the fields aligned like gofmt?
- Yes. Names, types and tags are padded into columns, so pasting the output into a file needs no reformatting.
- What about a key that is not a valid Go identifier?
- Punctuation is dropped and the parts are capitalised, so a key such as retry-after becomes RetryAfter with the original name kept in the tag.