go:generate to automate json tag generation for Go structs

aniket awati
Aug 9, 2017 · 1 min read

Go introduced :generate all the way back in 2014. I had written a quick fix tool to try it out, called easytags. Here is a way you can use it to automatically generate json,xml,sql or any other tags for your struct fields.

Usually you would have a large struct like this -

type Large struct {
Field string
OtherField string
AnotherField string
YetAnotherField string
UnnecessaryField string
ForgottenField string
.....
}

And you have to type out all your json tags for such structs. To generate these tags you’d just have to add a single line in the file.

//go:generate easytags $GOFILE

Now, if you run go generate, your struct looks like this -

//go:generate easytags $GOFILE

type Large struct {
Field string `json:"field"`
OtherField string `json:"other_field"`
AnotherField string `json:"another_field"`
YetAnotherField string `json:"yet_another_field"`
UnnecessaryField string `json:"unnecessary_field"`
ForgottenField string `json:"forgotten_field"`
}

If you use an IDE like Gogland, you could just add the generate line in the go file template, which removes the need to add the line also.

Easytags with IDE

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade