Gophers,
Context: Go 1.4 adds
the `go generate` command, which facilitates (limited) code generation
to solve certain problems when developing in Go, such as parser
generation (goyacc).
Problem: Go,
like most statically-typed languages, requires developers to explicitly
list fields and structures when unmarshaling JSON. In Go, this takes
the form of enumerating all the fields in a struct definition, and
potentially adding JSON struct tags for good measures. However, much
JSON "in the wild" is effectively strongly typed, which means that these
struct definitions can easily be generated automatically from a single
sample input.
Approach: A few years ago, I wrote
gojson,
a tool to automate this process, and I've been thrilled to see that so
many other Gophers have found it a useful tool in their toolbox as well.
In December, `go generate` was shipped with Go 1.4, which has made it
even more seamless to generate Go structs than I had originally
foreseen.
Proposal:
The gojson tool is analogous to goyacc. Both generate working Go code
which should be checked into source control, and are usually invoked
from `go generate`. goyacc is already one of the tools distributed with
Go. Given the prevalence of JSON (and especially Brad's recent
proposal
for dependency/vendoring in Go, which involves JSON configuration) it
may make sense to consider shipping a tool for facilitating the use of
JSON in Go.
Example:
Rather than writing out 89 fields manually, we can do
$ curl -s https://api.github.com/repos/chimeracoder/gojson | gojson -name=Repository
type Repository struct {
ArchiveURL string `json:"archive_url"`
AssigneesURL string `json:"assignees_url"`
BlobsURL string `json:"blobs_url"`
...
}
(fields omitted for brevity)
Which hooks in nicely to go generate:
//go:generate gojson -o repository.go -name "Repository" -pkg "github" -input json/repository.json
In many cases, the "json/repository.json" file is already present as it is also used by tests and/or examples, making this even more convenient for the developer.
Aditya