go-style-lint
A collection of linters (and corresponding
pre-commit
hooks) for enforcing some certain styles
in Go code
bare-nolint
bare-nolint
checks for bare
//nolint
directives in your code. Usage:
$ bare-nolint <filename>
These directives should always include the names of the linters being ignored,
e.g. //nolint:golint,unused
in order to:
- More clearly communicate intent behind the exclusion
- Help identify unnecessary directives, e.g. if a directive is for a linter
that is no longer run
Compare:
func helloHandler(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #2!\n") //nolint
}
With:
func helloHandler(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #2!\n") //nolint:errcheck
}
The latter helps, at a glance, to suggest the exception has something to do
with error checking, and gives anyone curious some more information they can
easily search to find out more.
Installation:
$ go install gitlab.com/matthewhughes/go-style-lint/cmd/bare-nolint@v0.4.0
Pre-commit hook:
- repo: https://gitlab.com/matthewhughes/go-style-lint
rev: v0.4.0
hooks:
- id: bare-nolint
ctx-style
ctx-style
checks that function declarations using context.Context
follow the
documented style guidelines:
Do not store Contexts inside a struct type; instead, pass a Context explicitly
to each function that needs it. The Context should be the first parameter,
typically named ctx
The supported names for the variable are: ctx
, _
, and parent
Usage:
$ ctx-style <filename>
// ok: context is first argument named ctx
func withCtx(ctx context.Context) {
doStuffWithCtx(ctx)
}
// ok: unused context's can use the name '_'
func withCtx(_ context.Context) {
doStuff()
}
// ok: `parent` is also an acceptable name
func makeNewCtx(parent context.Context) context.Context {
return enrichContext(parent)
}
// bad: context arg should be named 'ctx'
func withBadFx(myCtx context.Context) {
doStuffWithCtx(myCtx)
}
// bad: context arg should be first arg
func withBadFx(id int, Ctx context.Context) {
doStuffWithCtx(id, myCtx)
}
You can skip checking for this linter on a specific line with a comment
containing the string //no-ctx-style:
func newCtx(other context.Context) context.Context { //no-ctx-style:
return enrichCtx(parent)
}
Installation:
$ go install gitlab.com/matthewhughes/go-style-lint/cmd/ctx-style@v0.4.0
Pre-commit hook:
- repo: https://gitlab.com/matthewhughes/go-style-lint
rev: v0.4.0
hooks:
- id: ctx-style