go:generate to automate json tag generation for Go structs
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 $GOFILENow, 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.

