usestdlibvars

Table of Contents

  1. 解決する問題
  2. 設定
  3. オプション
  4. サンプル
    1. 検出例
    2. 修正例
  5. 注意点
  6. 参考リンク

usestdlibvars は Go 標準ライブラリで定義されている変数・定数を使うべき箇所でリテラル文字列が使われていないかを検出するツールです。

解決する問題

HTTP メソッドやステータスコードなどを文字列リテラルで書くと、タイポに気づきにくく、コードの可読性も下がります。標準ライブラリの定数を使えばコンパイル時にチェックされ、IDE の補完も効きます。

1
2
3
4
5
6
7
// Before: 文字列リテラルでタイポのリスクがある
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GETT" { // タイポに気づかない
// ...
}
w.WriteHeader(200)
}
1
2
3
4
5
6
7
// After: 標準ライブラリの定数を使用
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { // コンパイル時にチェックされる
// ...
}
w.WriteHeader(http.StatusOK)
}

設定

公式ドキュメント

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# .golangci.yml
version: "2"

linters:
enable:
- usestdlibvars
settings:
usestdlibvars:
http-method: true
http-status-code: true
time-weekday: true
time-month: true
time-layout: true
time-date-month: true

オプション

オプション デフォルト 説明
http-method bool true http.MethodGet 等の使用を提案
http-status-code bool true http.StatusOK 等の使用を提案
time-weekday bool true time.Weekday.String() の使用を提案
time-month bool false time.Month.String() の使用を提案
time-layout bool false time.Layout 等の使用を提案
time-date-month bool false time.Date 内の time.Month 使用を提案
crypto-hash bool false crypto.Hash.String() の使用を提案
default-rpc-path bool false rpc.DefaultXXPath の使用を提案
sql-isolation-level bool false sql.LevelXX.String() の使用を提案
tls-signature-scheme bool false tls.SignatureScheme.String() の使用を提案
constant-kind bool false constant.Kind.String() の使用を提案

サンプル

検出例

1
2
3
4
5
6
7
8
9
10
11
12
// usestdlibvars が警告するパターン

// 1. HTTP メソッド
req, _ := http.NewRequest("GET", url, nil) // should use http.MethodGet

// 2. HTTP ステータスコード
if resp.StatusCode == 404 { // should use http.StatusNotFound
// ...
}

// 3. time レイアウト
t, _ := time.Parse("2006-01-02", s) // should use time.DateOnly

修正例

1
2
3
4
5
6
7
8
9
10
// 1. HTTP メソッド
req, _ := http.NewRequest(http.MethodGet, url, nil)

// 2. HTTP ステータスコード
if resp.StatusCode == http.StatusNotFound {
// ...
}

// 3. time レイアウト
t, _ := time.Parse(time.DateOnly, s)

注意点

  • autofix に対応しているため golangci-lint run --fix で自動修正できる
  • デフォルトで有効なのは http-methodhttp-status-codetime-weekday のみ。プロジェクトに合わせて追加オプションを有効化すると効果が高い
  • time-layout を有効にすると "2006-01-02"time.DateOnly(Go 1.20+)のような提案もしてくれる

参考リンク