usestdlibvars は Go 標準ライブラリで定義されている変数・定数を使うべき箇所でリテラル文字列が使われていないかを検出するツールです。
解決する問題
HTTP メソッドやステータスコードなどを文字列リテラルで書くと、タイポに気づきにくく、コードの可読性も下がります。標準ライブラリの定数を使えばコンパイル時にチェックされ、IDE の補完も効きます。
1 2 3 4 5 6 7
| func handler(w http.ResponseWriter, r *http.Request) { if r.Method == "GETT" { } w.WriteHeader(200) }
|
1 2 3 4 5 6 7
| 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
| 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
|
req, _ := http.NewRequest("GET", url, nil)
if resp.StatusCode == 404 { }
t, _ := time.Parse("2006-01-02", s)
|
修正例
1 2 3 4 5 6 7 8 9 10
| req, _ := http.NewRequest(http.MethodGet, url, nil)
if resp.StatusCode == http.StatusNotFound { }
t, _ := time.Parse(time.DateOnly, s)
|
注意点
- autofix に対応しているため
golangci-lint run --fix で自動修正できる
- デフォルトで有効なのは
http-method、http-status-code、time-weekday のみ。プロジェクトに合わせて追加オプションを有効化すると効果が高い
time-layout を有効にすると "2006-01-02" → time.DateOnly(Go 1.20+)のような提案もしてくれる
参考リンク