背景
golangでAPIを構築しています。
コードを追加するたびに手動テストするのは面倒です。
そこで、自動でテストをする仕組みを調べています。
静的解析は速くチェックできるし、フィードバックもしやすいです。そこで、golangではどんなツールがあるのか調べました。
静的解析はgolangci-lint
静的解析はgolang-lint
というのがあります。
Goのソースコードのスタイルや可読性に関する基本的なチェックを行うツールです。
で、今はgolangci-lint
というのが一般的とのことです。
golangci-lint
は、golint
に加えて、errcheck
、staticcheck
、gocyclo
、ineffassign
など、多数のツールをまとめて実行します。
さらに、設定ファイル(YAML形式)を使って、各リントツールの有効/無効、警告レベルなどを細かくカスタマイズできます。
CI/CDにも組み込みやすいので、今はgolangci-lint
一択のようにです。
使い方
インストール方法は以下のリンクにあります。
https://github.com/golangci/golangci-lint
使うには以下のようにコマンドで。
golangci-lint run -v
パスすると、こんな感じで出力されます。
使っている当初は指摘が3つぐらい出てまして、関数の戻り値にエラーがないか確認しなさいというのがその指摘内容でした。
INFO golangci-lint has version 1.64.5 built with go1.24.0 from 0a603e49 on 2025-02-13T21:19:55Z
INFO [config_reader] Config search paths: [./ /home/yamadatt/git/lambda-api-gw-go /home/yamadatt/git /home/yamadatt /home /]
INFO [goenv] Read go env for 8.205455ms: map[string]string{"GOCACHE":"/home/yamadatt/.cache/go-build", "GOROOT":"/home/yamadatt/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.23.4.linux-amd64"}
INFO [lintersdb] Active 6 linters: [errcheck gosimple govet ineffassign staticcheck unused]
INFO [loader] Go packages loading at mode 8767 (imports|types_sizes|name|compiled_files|deps|exports_file|files) took 395.600228ms
INFO [runner/filename_unadjuster] Pre-built 0 adjustments in 1.350229ms
INFO [linters_context/goanalysis] analyzers took 0s with no stages
INFO [runner] Issues before processing: 26, after processing: 0
INFO [runner] Processors filtering stat (in/out): exclusion_rules: 26/0, invalid_issue: 26/26, exclusion_paths: 26/26, skip_files: 26/26, generated_file_filter: 26/26, path_absoluter: 26/26, filename_unadjuster: 26/26, cgo: 26/26, path_relativity: 26/26, skip_dirs: 26/26, identifier_marker: 26/26
INFO [runner] processing took 345.696µs with stages: exclusion_rules: 224.597µs, generated_file_filter: 84.269µs, path_relativity: 13.789µs, skip_dirs: 10.471µs, filename_unadjuster: 2.602µs, invalid_issue: 1.714µs, cgo: 1.436µs, identifier_marker: 1.436µs, max_same_issues: 1.046µs, path_absoluter: 1.03µs, nolint_filter: 702ns, sort_results: 351ns, skip_files: 276ns, fixer: 274ns, exclusion_paths: 273ns, diff: 225ns, source_code: 220ns, max_from_linter: 214ns, max_per_file_from_linter: 177ns, path_shortener: 160ns, uniq_by_line: 152ns, path_prettifier: 143ns, severity-rules: 139ns
INFO [runner] linters took 301.521762ms with stages: goanalysis_metalinter: 301.116282ms
INFO File cache stats: 0 entries of total size 0B
INFO Memory: 9 samples, avg is 44.9MB, max is 62.3MB
INFO Execution took 707.228889ms
ちなみに
snapでもインストールできますが、古いみたいなので上のリポジトリからインストールするのが良さそう。
sudo snap install golangci-lint
エラー内容。
error: This revision of snap "golangci-lint" was published using classic confinement and thus may
perform arbitrary system changes outside of the security sandbox that snaps are usually
confined to, which may put your system at risk.