✅

Go 言語のリンター・フォーマッター選定 2026

に公開
2026/02/09

最近、仕事とプライベートで Go 言語を使いはじめました。
それに際して、私自身が Go らしさを学びつつ、AI エージェントのガードレールも考慮しつつ、リンター・フォーマッターの整備をやってみました。

バージョン等

  • Go:v1.25.6
  • Golangci-lint:v2.7.2

前提:さすがに Golangci-lint は使う

フロントエンドとして Golangci-lint を使います。
Go のリンターは種類も多く、それらを一元管理し、並列に実行できるのは大変魅力的です。

実際、Golangci-lint を使うのがデファクトスタンダードっぽい雰囲気も感じてます。

選定基準(観点)

基本方針

Go のベストプラクティスを満たせるようにする

適用のデメリットが小さいものは積極的に採用する

  • リントの抑制を最小化する:例外的に無効化する(=適用しない)場面は少ない方が良いです。誤検知の少なさとも言えます。
  • チーム内での議論を最小化する:人によって好みが分かれそうなものは、最初のうちは避けておきたいです。

同種ツールの優先度

  1. 標準ツールである
  2. 公式の Go Tools にあるツールである
  3. メンテナンスが継続されている
  4. 人気がある

リンター一覧を見てみる

とりあえず、サポートされているリンターの一覧を見てみます。
golangci-lint help linters コマンドで表示できます。

結果 → 112個(多すぎ)
$ golangci-lint help linters
Enabled by default linters:
errcheck: Errcheck is a program for checking for unchecked errors in Go code. These unchecked errors can be critical bugs in some cases.
govet: Vet examines Go source code and reports suspicious constructs. It is roughly the same as 'go vet' and uses its passes. [auto-fix]
ineffassign: Detects when assignments to existing variables are not used. [fast]
staticcheck: It's the set of rules from staticcheck. [auto-fix]
unused: Checks Go code for unused constants, variables, functions and types.

Disabled by default linters:
arangolint: Opinionated best practices for arangodb client.
asasalint: Check for pass []any as any in variadic func(...any).
asciicheck: Checks that all code identifiers does not have non-ASCII symbols in the name. [fast]
bidichk: Checks for dangerous unicode character sequences. [fast]
bodyclose: Checks whether HTTP response body is closed successfully.
canonicalheader: Canonicalheader checks whether net/http.Header uses canonical header. [auto-fix]
containedctx: Containedctx is a linter that detects struct contained context.Context field.
contextcheck: Check whether the function uses a non-inherited context.
copyloopvar: A linter detects places where loop variables are copied. [fast, auto-fix]
cyclop: Checks function and package cyclomatic complexity. [fast]
decorder: Check declaration order and count of types, constants, variables and functions. [fast]
depguard: Go linter that checks if package imports are in a list of acceptable packages. [fast]
dogsled: Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()). [fast]
dupl: Detects duplicate fragments of code. [fast]
dupword: Checks for duplicate words in the source code. [fast, auto-fix]
durationcheck: Check for two durations multiplied together.
embeddedstructfieldcheck: Embedded types should be at the top of the field list of a struct, and there must be an empty line separating embedded fields from regular fields. [fast]
err113: Check errors handling expressions. [auto-fix]
errchkjson: Checks types passed to the json encoding functions. Reports unsupported types and reports occurrences where the check for the returned error can be omitted.
errname: Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
errorlint: Find code that can cause problems with the error wrapping scheme introduced in Go 1.13. [auto-fix]
exhaustive: Check exhaustiveness of enum switch statements.
exhaustruct: Checks if all structure fields are initialized.
exptostd: Detects functions from golang.org/x/exp/ that can be replaced by std functions. [auto-fix]
fatcontext: Detects nested contexts in loops and function literals. [auto-fix]
forbidigo: Forbids identifiers.
forcetypeassert: Find forced type assertions.
funcorder: Checks the order of functions, methods, and constructors. [fast]
funlen: Checks for long functions. [fast]
ginkgolinter: Enforces standards of using ginkgo and gomega. [auto-fix]
gocheckcompilerdirectives: Checks that go compiler directive comments (//go:) are valid. [fast]
gochecknoglobals: Check that no global variables exist.
gochecknoinits: Checks that no init functions are present in Go code. [fast]
gochecksumtype: Run exhaustiveness checks on Go "sum types".
gocognit: Computes and checks the cognitive complexity of functions. [fast]
goconst: Finds repeated strings that could be replaced by a constant.
gocritic: Provides diagnostics that check for bugs, performance and style issues. [auto-fix]
gocyclo: Computes and checks the cyclomatic complexity of functions. [fast]
godoclint: Checks Golang's documentation practice (godoc). [fast]
godot: Check if comments end in a period. [fast, auto-fix]
godox: Detects usage of FIXME, TODO and other keywords inside comments. [fast]
goheader: Check if file header matches to pattern. [fast, auto-fix]
gomoddirectives: Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast]
gomodguard: Allow and blocklist linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast]
goprintffuncname: Checks that printf-like functions are named with `f` at the end. [fast]
gosec: Inspects source code for security problems.
gosmopolitan: Report certain i18n/l10n anti-patterns in your Go codebase.
grouper: Analyze expression groups. [fast]
iface: Detect the incorrect use of interfaces, helping developers avoid interface pollution. [auto-fix]
importas: Enforces consistent import aliases. [auto-fix]
inamedparam: Reports interfaces with unnamed method parameters. [fast]
interfacebloat: A linter that checks the number of methods inside an interface. [fast]
intrange: Intrange is a linter to find places where for loops could make use of an integer range. [auto-fix]
iotamixing: Checks if iotas are being used in const blocks with other non-iota declarations. [fast]
ireturn: Accept Interfaces, Return Concrete Types.
lll: Reports long lines. [fast]
loggercheck: Checks key value pairs for common logger libraries (kitlog,klog,logr,slog,zap).
maintidx: Maintidx measures the maintainability index of each function. [fast]
makezero: Find slice declarations with non-zero initial length.
mirror: Reports wrong mirror patterns of bytes/strings usage. [auto-fix]
misspell: Finds commonly misspelled English words. [fast, auto-fix]
mnd: An analyzer to detect magic numbers. [fast]
modernize: A suite of analyzers that suggest simplifications to Go code, using modern language and library features.
musttag: Enforce field tags in (un)marshaled structs.
nakedret: Checks that functions with naked returns are not longer than a maximum size (can be zero). [fast, auto-fix]
nestif: Reports deeply nested if statements. [fast]
nilerr: Find the code that returns nil even if it checks that the error is not nil.
nilnesserr: Reports constructs that checks for err != nil, but returns a different nil value error.
nilnil: Checks that there is no simultaneous return of `nil` error and an invalid value.
nlreturn: Checks for a new line before return and branch statements to increase code clarity. [fast, auto-fix]
noctx: Detects function and method with missing usage of context.Context.
noinlineerr: Disallows inline error handling (`if err := ...; err != nil {`).
nolintlint: Reports ill-formed or insufficient nolint directives. [fast, auto-fix]
nonamedreturns: Reports all named returns.
nosprintfhostport: Checks for misuse of Sprintf to construct a host with port in a URL. [fast]
paralleltest: Detects missing usage of t.Parallel() method in your Go test.
perfsprint: Checks that fmt.Sprintf can be replaced with a faster alternative. [auto-fix]
prealloc: Find slice declarations that could potentially be pre-allocated. [fast]
predeclared: Find code that shadows one of Go's predeclared identifiers. [fast]
promlinter: Check Prometheus metrics naming via promlint. [fast]
protogetter: Reports direct reads from proto message fields when getters should be used. [auto-fix]
reassign: Checks that package variables are not reassigned.
recvcheck: Checks for receiver type consistency.
revive: Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [auto-fix]
rowserrcheck: Checks whether Rows.Err of rows is checked successfully.
sloglint: Ensure consistent code style when using log/slog. [auto-fix]
spancheck: Checks for mistakes with OpenTelemetry/Census spans.
sqlclosecheck: Checks that sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query are closed.
tagalign: Check that struct tags are well aligned. [fast, auto-fix]
tagliatelle: Checks the struct tags.
testableexamples: Linter checks if examples are testable (have an expected output). [fast]
testifylint: Checks usage of github.com/stretchr/testify. [auto-fix]
testpackage: Linter that makes you use a separate _test package. [fast]
thelper: Thelper detects tests helpers which do not start with the t.Helper() method.
tparallel: Tparallel detects inappropriate usage of t.Parallel() method in your Go test codes.
unconvert: Remove unnecessary type conversions.
unparam: Reports unused function parameters.
unqueryvet: Detects SELECT * in SQL queries and SQL builders, preventing performance issues and encouraging explicit column selection. [fast]
usestdlibvars: A linter that detect the possibility to use variables/constants from the Go standard library. [fast, auto-fix]
usetesting: Reports uses of functions with replacement inside the testing package. [auto-fix]
varnamelen: Checks that the length of a variable's name matches its scope.
wastedassign: Finds wasted assignment statements.
whitespace: Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc. [fast, auto-fix]
wrapcheck: Checks that errors returned from external packages are wrapped.
wsl_v5: Add or remove empty lines. [auto-fix]
zerologlint: Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`.
wsl [deprecated]: Add or remove empty lines. [fast, auto-fix]

Claude Code でリンターを選定する

こんなときこそ生成 AI の出番だろうということで、ちょうど作っていた Agent Skill go-professional を活用し、選定してみることにしました。

雑に依頼してみる

❯ Agent Skill `go-professional` に基づき、特に必要なリンターを選定して。 
選定結果 - 1

Recommendations Based on Go Professional Best Practices

The following recommendations are based on:

  • Effective Go — Official idiomatic Go patterns
  • Go Code Review Comments — Common code review feedback
  • Google Go Style Guide — Professional team standards

Essential (Strongly Recommended)

These linters enforce core Go best practices and should always be enabled.

Linter Rule Category Rationale
errcheck Error handling Never ignore errors (default enabled)
govet Bug detection Detect suspicious constructs (default enabled)
staticcheck Multiple Comprehensive static analysis (default enabled)
unused Package design Avoid unnecessary exports (default enabled)
gosec Security Detect security problems
errorlint Error handling Correct Go 1.13 error wrapping (%w)
gocritic Multiple Comprehensive bug/performance/style checks
revive Multiple Naming and style (golint successor)

These linters catch common mistakes and improve code quality.

Linter Rule Category Rationale
nilerr Error handling Detect returning nil when err != nil
bodyclose Resource management Detect HTTP response body leaks
contextcheck Concurrency Ensure correct context propagation
noctx Concurrency Detect missing context.Context
unparam Package design Detect unused parameters
unconvert Clean code Remove unnecessary type conversions
misspell Comments Detect spelling errors
thelper Testing Detect missing t.Helper()
exhaustive Control flow Check switch statement exhaustiveness
dupword Comments Detect duplicate words

These linters provide additional value for professional codebases.

Linter Rule Category Rationale
errname Naming Error naming convention (Err prefix)
predeclared Naming Avoid shadowing predeclared identifiers
iface Interfaces Check interface design
containedctx Interfaces Avoid context.Context in structs
nestif Control flow Avoid deep nesting (maintain happy path)
gocognit Maintainability Cognitive complexity (readability)
testifylint Testing Check testify usage
paralleltest Testing Detect missing t.Parallel()
importas Imports Consistent import aliases
godot Comments Comment ending with period
wrapcheck Error handling Enforce wrapping external errors
modernize Clean code Use modern Go features
usestdlibvars Clean code Use stdlib constants
copyloopvar Bug prevention Detect loop variable copies

These linters are too strict or conflict with Go idioms.

Linter Reason
exhaustruct Forcing all field initialization is excessive
varnamelen Short names are Go convention
gochecknoglobals Global variables are sometimes appropriate
gochecknoinits init functions are sometimes appropriate
nonamedreturns Named returns are useful when used properly
ireturn Returning interfaces is sometimes appropriate
wsl_v5 gofmt is sufficient
lll Strict line length limits are unnecessary
mnd Banning all magic numbers is excessive

Example Configuration

Based on the above recommendations, here is a sample .golangci.yml:

linters:
  enable:
    # Essential
    - gosec
    - errorlint
    - gocritic
    - revive
    # Highly Recommended
    - nilerr
    - bodyclose
    - contextcheck
    - noctx
    - unparam
    - unconvert
    - misspell
    - thelper
    - exhaustive
    - dupword
    # Recommended
    - errname
    - predeclared
    - iface
    - containedctx
    - nestif
    - gocognit
    - testifylint
    - paralleltest
    - importas
    - godot
    - wrapcheck
    - modernize
    - usestdlibvars
    - copyloopvar

おっ、すでになんかそれっぽいですね。

条件を足す

nolint する機会が多かったり、人によって好みが分かれやすいものは、導入すると形骸化したり生産性を落としたりするので、避けます。

逆に、そうではないものは積極的に採用して良いと考えます。

❯ 加えて、以下のものは積極的に採用するようにしたいです。
- 例外的にリンターを無効化する場面が少ないもの
- 人によって好みが分かれないもの
選定結果 - 2

Recommendations Based on Go Professional Best Practices

The following recommendations are based on:

  • Effective Go — Official idiomatic Go patterns
  • Go Code Review Comments — Common code review feedback
  • Google Go Style Guide — Professional team standards

Selection Criteria

Linters are evaluated on two key factors:

Rating Meaning
◎ No exceptions needed, objective detection (highest priority)
○ Exceptions rare, not preference-dependent
△ Occasional exceptions needed, or configuration-dependent
× Many exceptions needed, or preference-dependent

Tier 1: Highest Priority (No Exceptions, Objective)

These linters detect objective issues that should always be fixed.
They rarely require //nolint directives.

Linter Category Rationale
errcheck Error handling Unchecked errors are bugs (default)
govet Bug detection Suspicious constructs (default)
staticcheck Multiple Comprehensive static analysis (default)
unused Dead code Unused code is objective (default)
ineffassign Dead code Unused assignments are objective (default)
gosec Security Security issues must be fixed
bidichk Security Dangerous unicode sequences
errorlint Error handling Go 1.13+ standard error wrapping
nilerr Bug detection Returning nil when err != nil is a bug
bodyclose Resource leak HTTP response body leaks
unconvert Dead code Unnecessary conversions are objective
wastedassign Dead code Wasted assignments are objective
copyloopvar Bug detection Loop variable capture bugs
misspell Comments Spelling errors are objective
dupword Comments Duplicate words are objective

Tier 2: High Priority (Exceptions Rare)

These linters catch important issues with minimal false positives.

Linter Category Rationale
contextcheck Concurrency Context propagation is important
noctx Concurrency Missing context.Context
unparam Dead code Unused parameters are objective
thelper Testing t.Helper() is standard practice
predeclared Naming Shadowing predeclared identifiers causes bugs
errname Naming Error naming convention is clear
asciicheck Naming Non-ASCII identifiers are objective
usestdlibvars Clean code Using stdlib constants is objective
intrange Modernization Go 1.22+ integer range syntax
modernize Modernization Modern Go features

These linters provide value but may require occasional //nolint.

Linter Category Note
gocritic Multiple Some rules may need configuration
revive Multiple Configuration-dependent
exhaustive Control flow Intentional default cases exist
testifylint Testing When using testify
iface Interfaces Interface design guidance

Use with Caution (Many Exceptions or Preference-Dependent)

These linters often require //nolint or cause team disagreements.

Linter Issue
wrapcheck Internal package errors often don't need wrapping
paralleltest Some tests cannot run in parallel
godot Comment style is preference
gocognit Threshold setting is subjective
nestif Threshold setting is subjective
containedctx Some frameworks require context in structs

These linters are too strict or conflict with Go idioms.

Linter Reason
exhaustruct Forcing all field initialization is excessive
varnamelen Short names are Go convention
gochecknoglobals Global variables are sometimes appropriate
gochecknoinits init functions are sometimes appropriate
nonamedreturns Named returns are useful when used properly
ireturn Returning interfaces is sometimes appropriate
wsl_v5 gofmt is sufficient
lll Strict line length limits are unnecessary
mnd Banning all magic numbers is excessive
noinlineerr Inline error handling is common Go idiom

Example Configuration

Based on the above recommendations, here is a sample .golangci.yml.
Tier 1 and Tier 2 linters are enabled by default.

linters:
  enable:
    # Tier 1: Highest Priority (no exceptions, objective)
    - gosec
    - bidichk
    - errorlint
    - nilerr
    - bodyclose
    - unconvert
    - wastedassign
    - copyloopvar
    - misspell
    - dupword
    # Tier 2: High Priority (exceptions rare)
    - contextcheck
    - noctx
    - unparam
    - thelper
    - predeclared
    - errname
    - asciicheck
    - usestdlibvars
    - intrange
    - modernize
    # Tier 3: Recommended (occasional exceptions)
    - gocritic
    - revive
    - exhaustive
    - testifylint
    - iface

良い感じです。
これをベースに検討を進めてみます。

Tier 1: Highest Priority (No Exceptions, Objective) から選定していく

改めて、これが一覧。

Linter Category Rationale
gosec Security Security issues must be fixed
bidichk Security Dangerous unicode sequences
errorlint Error handling Go 1.13+ standard error wrapping
nilerr Bug detection Returning nil when err != nil is a bug
bodyclose Resource leak HTTP response body leaks
unconvert Dead code Unnecessary conversions are objective
wastedassign Dead code Wasted assignments are objective
copyloopvar Bug detection Loop variable capture bugs
misspell Comments Spelling errors are objective
dupword Comments Duplicate words are objective

ここから、不要なものを取り除いていきます。

ineffassign / wastedassign

これらは staticcheck の SA4006 でほぼカバーできているので、一旦無効化しておいて良いでしょう。

copyloopvar

これは Go 1.22 で言語レベルで解決している ので、今は不要です。

nilerr

何かのチェックをしてエラーの場合 nil やデフォルト値を返すケースも普通にあるし、別に設計上悪いとも思わないので、無効化しておきます。

misspell / dupword

実際は誤検知が多いし、Go のリンターで設定すべきではないので不要です。

スペルチェック自体は、用語を強制して後の検索性を高める意味で、有効と考えています。
しかし経験上、固有名詞や日本語のローマ字表記をミススペルと判断されてしまいがちで、辞書が肥大化していく傾向にあるので注意が必要です。

同じ単語の連続も、普通にあり得ますからね。

共通して言えるのは、Go 以外のもの(Markdown ドキュメントや YAML 設定ファイル等)にも適用すべき、ということです。
言語レベルのリンターで検知させるのはちょっと違うかなぁと思います。

というわけで残ったやつ

普通に有用かつ普遍的なものが残った気がします。

Linter Category Default
gosec Security No
bidichk Security No
errorlint Error handling No
bodyclose Resource leak No
unconvert Dead code No

補足:errorlint がアーカイブされている?

GitHub の polyfloyd/go-errorlint がアーカイブされているのでメンテナンス終了か?と思ったのですが、Codeberg に移行したとのことでした。

Tier 2: High Priority (Exceptions Rare) から選定していく

一覧はこちら。

Linter Category Rationale
contextcheck Concurrency Context propagation is important
noctx Concurrency Missing context.Context
thelper Testing t.Helper() is standard practice
predeclared Naming Shadowing predeclared identifiers causes bugs
errname Naming Error naming convention is clear
asciicheck Naming Non-ASCII identifiers are objective
usestdlibvars Clean code Using stdlib constants is objective
intrange Modernization Go 1.22+ integer range syntax
modernize Modernization Modern Go features
whitespace Formatting Unnecessary newlines are objective (auto-fix)

基本不要と思われますが、気になるものをピックして咀嚼してみます。

usestdlibvars

標準ライブラリの定数を使うように促すやつ。
コーディング規約としてよく議論されるところな気がするので、有効にして強制したい気持ちはあります。

マッピングの定義 を見ると、どの辺が対象になるか掴めますね。

ただ、HTTP ステータスコードとして 500 の方が分かりやすいっていうのも理解できるし、日本人なら月は数字の方が分かりやすいだろうし、どうでしょう…。

一旦有効にして様子を見ることにしました。

modernize

Go の最近の機能を提案してくれるやつ。

例:any: interface{} can be replaced by any ← 1.18 で any が追加されたのでそれを使えるよ、という提案

言語仕様のアップデートに半強制的に追従できるので、良いかもです。

whitespace

不要な空行を消してくるだけでそこまで意味はないけど、(私のように)几帳面な人は気になりますよね。

…と思ったのですが、フォーマッターで出てくる gofumpt でカバーできるので、これは無効にしておきます。

役立つけど例外が多め(nolint しがち)なものです。

exhaustive

switch 文での Enum 網羅性をチェックするやつです。
といっても Go 言語は Enum 型は直接サポートしていないので、iota で構成する定数(よくあるパターン)に対するチェックです。

個人的には Enum でストリクトに表現していくのは、保守性を鑑みても推奨できると思いますし、有効にしておきます。

testifylint

テスティングライブラリ Testify を使うなら、有効にしておいても良さそうです。

その他

ざっと見た感じ、直ちに必要そうなものはない印象でした。
内容は把握しつつ、欲しくなったら入れる感じにします。

結論:リンター選定結果

以下を採用することにしました。

Linter Category Default
govet Bug detection Yes
staticcheck Static analysis Yes
errcheck Error handling Yes
unused Dead code Yes
gosec Security No
bidichk Security No
errorlint Error handling No
bodyclose Resource leak No
unconvert Dead code No
usestdlibvars Clean code No
modernize Modernization No
exhaustive Control flow No

フォーマッターを選定する

リンターほど多くないので、手動で見ていきます。

6種類ありますね。

$ golangci-lint help formatters
Disabled by default formatters:
gci: Check if code and import statements are formatted, with additional rules.
gofmt: Check if the code is formatted according to 'gofmt' command.
gofumpt: Check if code and import statements are formatted, with additional rules.
goimports: Checks if the code and import statements are formatted according to the 'goimports' command.
golines: Checks if code is formatted, and fixes long lines.
swaggo: Check if swaggo comments are formatted.

不要なフォーマッターを除外する

gci

Go Tools に含まれる goimports を採用するので、こちらは不要です。

golines

行を単純な長さを基準にしてフォーマットするとセマンティクス的におかしくなることがあるので、あまり好きじゃないです。

swaggo

Swagger の話は今しなくていいよね。

フォーマッター構成を検討する

残ったものの組み合わせとして、以下の2択ですね。

  • gofmt + goimports
  • gofumpt + goimports

Go の標準は gofmt です。

gofumpt は gofmt との後方互換性を維持しつつ、いくつかのルール が追加されています。
これらのルールをざっと眺めてみましたが、特に変なものは無いし、むしろこれくらい強制した方が統一感が出て良い気がします。
AI にコード書かせる時代だし。
やりすぎなルールは -extra オプションに逃がしており、ちょうど良いバランスで使えるよう配慮されています。

結論:フォーマッター選定結果

Formatter Category
gofumpt Code Formatting
goimports Import Organization

まとめ

最終的な設定ファイルがこちらです。

https://github.com/23prime/claude-launcher/blob/main/.golangci.yml

今後開発を通して更新していくと思いますので、なにか気づきがあったら更新します。多分。

参考

Discussion