A Go linter that enforces field tags in (un)marshaled structs
musttag
checks that exported fields of a struct passed to a Marshal
-like function are annotated with the relevant tag:
// BAD:
var user struct {
Name string
}
data, err := json.Marshal(user)
// GOOD:
var user struct {
Name string `json:"name"`
}
data, err := json.Marshal(user)
The rational from Uber Style Guide:
The serialized form of the structure is a contract between different systems. Changes to the structure of the serialized form, including field names, break this contract. Specifying field names inside tags makes the contract explicit, and it guards against accidentally breaking the contract by refactoring or renaming fields.
musttag
supports these packages out of the box:
encoding/json
encoding/xml
gopkg.in/yaml.v3
github.com/BurntSushi/toml
github.com/mitchellh/mapstructure
- ...and any custom one
go install github.com/junk1tm/musttag/cmd/musttag@latest
brew install junk1tm/tap/musttag
Download a prebuilt binary from the Releases page.
As a standalone binary:
musttag ./...
Via go vet
:
go vet -vettool=$(which musttag) ./...
The -fn=name:tag:argpos
flag can be used to report functions from custom packages, where
name
is the full name of the function, including the packagetag
is the struct tag whose presence should be ensuredargpos
is the position of the argument to check
For example, to support the sqlx.Get
function:
musttag -fn="github.com/jmoiron/sqlx.Get:db:1" ./...