Skip to content

πŸš” Enforce field tags in (un)marshaled structs

License

Notifications You must be signed in to change notification settings

go-simpler/musttag

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

95 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

musttag

checks pkg.go.dev goreportcard codecov

A Go linter that enforces field tags in (un)marshaled structs.

πŸ“Œ About

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.

πŸš€ Features

The following packages are supported out of the box:

In addition, any custom package can be added to the list.

πŸ“¦ Install

musttag is integrated into golangci-lint, and this is the recommended way to use it.

To enable the linter, add the following lines to .golangci.yml:

linters:
  enable:
    - musttag

Alternatively, you can download a prebuilt binary from the Releases page to use musttag standalone.

πŸ“‹ Usage

Run golangci-lint with musttag enabled. See the list of available options to configure the linter.

When using musttag standalone, pass the options as flags.

Custom packages

To report a custom function, you need to add its description to .golangci.yml. The following is an example of adding support for hclsimple.Decode:

linters-settings:
  musttag:
    functions:
        # The full name of the function, including the package.
      - name: github.com/hashicorp/hcl/v2/hclsimple.Decode
        # The struct tag whose presence should be ensured.
        tag: hcl
        # The position of the argument to check.
        arg-pos: 2

The same can be done via the -fn=<name:tag:arg-pos> flag when using musttag standalone:

musttag -fn="github.com/hashicorp/hcl/v2/hclsimple.DecodeFile:hcl:2" ./...