lint で止めているもの(24)
make check で止まる。層ごとの依存の向きと、使う道具の決まり。
| ルール | 止めるリンター | 出典 |
|---|
| 依存は cmd → adapter → usecase → domain の一方向 | depguard(層ごとの import の禁止) | AGENTS.md |
| domain は標準ライブラリと他の集約の domain だけを import する | depguard(strict) | coding-rules.md |
| usecase は database/sql・net/http・gin を import しない | depguard(strict) | AGENTS.md |
| adapter 同士は import しない。adapter は infra を import しない | depguard | AGENTS.md |
| handler は database/sql、repository は net/http と gin を import しない | depguard | coding-rules.md |
| 外部モジュールは pgx と gin だけ(モック生成ツール・DI フレームワークを入れない) | gomodguard_v2 | AGENTS.md |
| repository は conn(ctx, r.db) 経由で DB にアクセスする | forbidigo | coding-rules.md |
| usecase から他の usecase を呼ばない | forbidigo | coding-rules.md |
| util / utils / common パッケージを作らない | revive(package-naming) | AGENTS.md |
| コンストラクタは struct を返す | ireturn | AGENTS.md |
| context を struct のフィールドに持たない | containedctx | coding-rules.md |
| ログは log/slog を使う(fmt.Println / log を使わない) | forbidigo・sloglint | coding-rules.md |
呼んではいけない関数・型と、置き場所の決まり。ルール名を押すと、指摘される書き方と設定を見られる。
lint にできないもの(15)
設定だけでは表せないので、coding-rules.md と adding-a-feature.md に書いて守る。
| ルール | lint にできない理由 |
|---|
| usecase の interface は port.go に置く | ファイル名と型宣言を組み合わせた条件は、設定だけでは書けない |
| domain に json / db タグを付けない。フィールドは非公開にする | タグやフィールドが「あること」を禁止するリンターがない |
| usecase は domain の型を返さず、Output に詰め替える | 戻り値の型を層ごとに縛れない |
| *gin.Context を usecase に渡さない(c.Request.Context() を渡す) | c を context.Context として渡しても、呼び出しの形では区別できない |
| ドメインエラーを足したら errorMappings にも足す | 2 つのファイルの対応は lint の対象外。足し忘れると 500 になる |
| ErrNoRows や 0 件更新を ErrNotFound に変換する | 処理の中身の正しさは lint の対象外 |
| SQL の書き方、ORDER BY の最後に id を足す | SQL の文字列の中身は検査できない |
| 外部サービスの呼び出しはコミットの後に行う | 処理の順序は lint の対象外 |
| HTTP メソッドとステータスの対応(作成 201、削除 204 など) | 処理の中身の正しさは lint の対象外 |
| ID は user/id.go と同じ形(標準ライブラリの uuid)で書く | 実装の形をそろえる決まりは、設定では表せない |
| 数値のフィールドは New で上限も検証する | 値の範囲の正しさは lint の対象外 |
| 外部キー違反を参照先の集約の ErrNotFound に変換する | 処理の中身の正しさは lint の対象外 |
| マイグレーションの書き方(型の対応、ON DELETE の明記、外部キーのインデックス) | SQL ファイルは Go の lint の対象外 |
| API を変えたら openapi.yaml も同じ書き方で更新する | YAML とコードの対応は lint の対象外 |
| テストの書き方(テーブルのフィールドの順、t.Run の中の順序) | 書き方の型は、設定では表せない |
指摘される
1−import "net/http"◀2 3−// StatusOf はドメインエラーを HTTP ステータスに変換する。4−func StatusOf(err error) int {5− if err != nil {6− return http.StatusBadRequest7− }8−空行9− return http.StatusOK10−}
1行目import 'net/http' is not allowed from list 'domain': domain は HTTP を知らない
指摘されない
1+import "errors"2 3+// ErrInvalidName は名前が不正なときのドメインエラー。4+var ErrInvalidName = errors.New("invalid name")
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
1−import (2− "context"3− "database/sql"◀4−)5 6 // GetUserName はユーザー名を取得する。7−func GetUserName(ctx context.Context, db *sql.DB, id string) (string, error) {8− var name string9−空行10− err := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)11−空行12− return name, err13 }
3行目import 'database/sql' is not allowed from list 'usecase': usecase は port(interface) 経由で永続化する
wrapcheck も同じ箇所を指摘します
指摘されない
1+import "context"2+空行3+// UserNameFinder は usecase が必要とする永続化の窓口(port)。4+type UserNameFinder interface {5+ FindName(ctx context.Context, id string) (string, error)6+}7 8 // GetUserName はユーザー名を取得する。9+func GetUserName(ctx context.Context, repo UserNameFinder, id string) (string, error) {10+ return repo.FindName(ctx, id)11 }
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
1−import "example.com/go-clean/internal/adapter/repository"◀2 3−// UserHandler はユーザー API のハンドラ。4 type UserHandler struct {5− Repo *repository.UserRepository6 }
1行目import 'example.com/go-clean/internal/adapter/repository' is not allowed from list 'adapter': adapter 同士は依存しない(つなぐのは cmd の DI)
指摘されない
1+import "context"2 3+type userUsecase interface {4+ Create(ctx context.Context, name string) error5+}6+空行7+// UserHandler は usecase の interface だけを知る。8 type UserHandler struct {9+ Users userUsecase10 }11+空行12+// Create はユーザーを作成する。13+func (h *UserHandler) Create(ctx context.Context, name string) error {14+ return h.Users.Create(ctx, name)15+}
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
1−import "example.com/go-clean/internal/infra/database"◀2 3−// UserRepository は users テーブルを扱う。4 type UserRepository struct {5− DB *database.DB6 }
1行目import 'example.com/go-clean/internal/infra/database' is not allowed from list 'adapter': adapter は infra に依存しない(必要なものは cmd から注入で受け取る)
指摘されない
1+import (2+ "context"3+ "database/sql"4+ "fmt"5+)6 7+// UserRepository は *sql.DB をコンストラクタで受け取る。8 type UserRepository struct {9+ db *sql.DB10 }11+空行12+// NewUserRepository は UserRepository を生成する。13+func NewUserRepository(db *sql.DB) *UserRepository {14+ return &UserRepository{db: db}15+}16+空行17+// Ping は DB に接続できるかを確かめる。18+func (r *UserRepository) Ping(ctx context.Context) error {19+ if err := r.db.PingContext(ctx); err != nil {20+ return fmt.Errorf("ping: %w", err)21+ }22+空行23+ return nil24+}
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
1−import "example.com/go-clean/internal/domain/user"◀2 3−// DefaultUserName は初期データのユーザー名。4−var DefaultUserName = user.DefaultName
1行目import 'example.com/go-clean/internal/domain/user' is not allowed from list 'infra': infra は技術的な土台のみ。ビジネスロジックに依存しない
指摘されない
1+import "time"2 3+// Config はアプリの設定。4+type Config struct {5+ Addr string6+ ShutdownTimeout time.Duration7+}
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
例外internal/adapter/repository/tx.go の、パニック中にロールバックが失敗したときのログだけは、エラーを返す先がないので対象外にしている。
指摘される
internal/usecase/report.go
1 package usecase2 3 import (4 "context"5 "fmt"6− "log/slog"◀7 )8 9 // ReportUsecase はレポートに関するユースケース。10 type ReportUsecase struct {11 store ReportStore12 }13 14 // Create はレポートを保存する。15 func (uc *ReportUsecase) Create(ctx context.Context, body string) error {16 if err := uc.store.Save(ctx, body); err != nil {17− slog.ErrorContext(ctx, "save report", "error", err)18−空行19 return fmt.Errorf("save report: %w", err)20 }21 22 return nil23 }
6行目import 'log/slog' is not allowed from list 'nolog': ログは handler の writeError でだけ出す。エラーは %w で包んで返す
指摘されない
internal/usecase/report.go
1 package usecase2 3 import (4 "context"5 "fmt"6 )7 8 // ReportUsecase はレポートに関するユースケース。9 type ReportUsecase struct {10 store ReportStore11 }12 13 // Create はレポートを保存する。14 func (uc *ReportUsecase) Create(ctx context.Context, body string) error {15 if err := uc.store.Save(ctx, body); err != nil {16 return fmt.Errorf("save report: %w", err)17 }18 19 return nil20 }
.golangci.yml の設定
1 linters:2 settings:3 depguard:4 rules:5 nolog:6 list-mode: lax7 files:8 - "**/internal/domain/**"9 - "**/internal/usecase/**"10 - "**/internal/adapter/**"11 - "!**/internal/adapter/handler/**"12 deny:13 - pkg: log/slog14 desc: "ログは handler の writeError でだけ出す。エラーは %w で包んで返す"15 exclusions:16 rules:17 - path: internal/adapter/repository/tx\.go # パニック中のロールバック失敗は返す先がないのでログに残す18 linters: [depguard]19 text: ログは handler の writeError
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
internal/usecase/name.go
1−package usecase2 3−import "example.com/go-clean/internal/helper"◀4 5 // NormalizeName は名前の前後の空白を除く。6 func NormalizeName(name string) string {7− return helper.TrimSpace(name)8 }
3行目import 'example.com/go-clean/internal/helper' is not allowed from list 'nodir': helper パッケージを作らない。置き場所は層で決める
指摘されない
internal/domain/user/name.go
1+package user2 3+import "strings"4 5 // NormalizeName は名前の前後の空白を除く。6 func NormalizeName(name string) string {7+ return strings.TrimSpace(name)8 }
.golangci.yml の設定
1 linters:2 settings:3 depguard:4 rules:5 nodir:6 list-mode: lax7 files:8 - $all9 deny:10 - pkg: example.com/go-clean/pkg11 desc: "pkg/ ディレクトリを作らない。置き場所は層で決める"12 - pkg: example.com/go-clean/internal/helper13 desc: "helper パッケージを作らない。置き場所は層で決める"14 - pkg: example.com/go-clean/internal/shared15 desc: "shared パッケージを作らない。置き場所は層で決める"
depguard — パッケージごとに import してよいもの/いけないものを決め、クリーンアーキテクチャの依存方向(cmd → adapter → usecase → domain)を守らせる。 設定: rules: domain / usecase(strict), handler / repository / infra(lax) / nolog(slog は handler だけ) / nodir(pkg・helper・shared)
指摘される
1 import (2 "log/slog"3 "os"4 )5 6−func init() {◀7− slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))8 }
6行目don't use `init` function
指摘されない
1 import (2 "log/slog"3 "os"4 )5 6+// NewLogger はロガーを作る。main で slog.SetDefault に渡す。7+func NewLogger() *slog.Logger {8+ return slog.New(slog.NewJSONHandler(os.Stdout, nil))9 }
gochecknoinits — init 関数を禁止する。初期化と DI は cmd/api/main.go に手書きするというルールを守らせる。
指摘される
1−// Store は名前の保存先。2−type Store interface {3− Save(name string)4−}5−空行6−type memoryStore struct {7 names []string8 }9 10−func (s *memoryStore) Save(name string) {11 s.names = append(s.names, name)12 }13−空行14−// NewStore は保存先を作る。15−func NewStore() Store {◀16− return &memoryStore{}17−}
15行目NewStore returns interface (example.com/go-clean/internal/cases/q_ireturn_bad.Store)
iface・revive も同じ箇所を指摘します
指摘されない
1+// MemoryStore はメモリ上の保存先。2+type MemoryStore struct {3 names []string4 }5 6+// NewMemoryStore は保存先を作る。7+func NewMemoryStore() *MemoryStore {8+ return &MemoryStore{}9+}10+空行11+// Save は名前を保存する。12+func (s *MemoryStore) Save(name string) {13 s.names = append(s.names, name)14 }
ireturn — 関数が interface を返すことを禁止する。「コンストラクタは struct を返す」というルールを守らせる。 設定: allow: error / empty / stdlib
指摘される
1−import "context"2 3 // Worker はジョブを処理する。4 type Worker struct {5− Ctx context.Context◀6 Name string7 }
5行目found a struct that contains a context.Context field
指摘されない
1+import (2+ "context"3+ "log/slog"4+)5 6 // Worker はジョブを処理する。7 type Worker struct {8 Name string9 }10+空行11+// Run はジョブを処理する。12+func (w *Worker) Run(ctx context.Context) {13+ slog.InfoContext(ctx, "run", "name", w.Name)14+}
containedctx — 構造体のフィールドに context.Context を持たせることを禁止する。context は引数で渡す。
指摘される
1 import "fmt"2 3 // UserFinder はユーザーを探す。4 type UserFinder interface {◀5− // FindName は ID からユーザー名を返す。6− FindName(id string) (string, error)7−}8−空行9−// NameLoader はユーザー名を読み込む。10−type NameLoader interface {◀11 // FindName は ID からユーザー名を返す。12 FindName(id string) (string, error)13 }14 15 // Label は表示名を返す。16 func Label(f UserFinder, id string) (string, error) {17 name, err := f.FindName(id)18 if err != nil {19 return "", fmt.Errorf("find name: %w", err)20 }21 22 return "@" + name, nil23 }24 25 // Exists はユーザーがいるかを返す。26−func Exists(l NameLoader, id string) bool {27− _, err := l.FindName(id)28 29 return err == nil30 }
4行目identical: interface 'UserFinder' contains identical methods or type constraints with another interface, causing redundancy (see: NameLoader)
10行目identical: interface 'NameLoader' contains identical methods or type constraints with another interface, causing redundancy (see: UserFinder)
指摘されない
1 import "fmt"2 3 // UserFinder はユーザーを探す。4 type UserFinder interface {5 // FindName は ID からユーザー名を返す。6 FindName(id string) (string, error)7 }8 9 // Label は表示名を返す。10 func Label(f UserFinder, id string) (string, error) {11 name, err := f.FindName(id)12 if err != nil {13 return "", fmt.Errorf("find name: %w", err)14 }15 16 return "@" + name, nil17 }18 19 // Exists はユーザーがいるかを返す。20+func Exists(f UserFinder, id string) bool {21+ _, err := f.FindName(id)22 23 return err == nil24 }
iface — interface の無駄を検出する。中身が同じ interface の重複と、パッケージ内で一度も呼ばれないメソッドを報告する。 設定: enable: [identical, unused, unusedmethod]
指摘される
1 import (2 "context"3 "fmt"4 )5 6 // Store は保存先。7 type Store interface {8 // Save は値を保存する。9 Save(ctx context.Context, v string) error10− // Delete は値を削除する。11− Delete(ctx context.Context, v string) error◀12 }13 14 // Keep は値を保存する。15 func Keep(ctx context.Context, s Store, v string) error {16 if err := s.Save(ctx, v); err != nil {17 return fmt.Errorf("save: %w", err)18 }19 20 return nil21 }
11行目unusedmethod: method 'Delete()' is declared on interface 'Store' but not used within the package
指摘されない
1 import (2 "context"3 "fmt"4 )5 6 // Store は保存先。7 type Store interface {8 // Save は値を保存する。9 Save(ctx context.Context, v string) error10 }11 12 // Keep は値を保存する。13 func Keep(ctx context.Context, s Store, v string) error {14 if err := s.Save(ctx, v); err != nil {15 return fmt.Errorf("save: %w", err)16 }17 18 return nil19 }
iface — interface の無駄を検出する。中身が同じ interface の重複と、パッケージ内で一度も呼ばれないメソッドを報告する。 設定: enable: [identical, unused, unusedmethod]
指摘される
1 // Store は値を保持する。2 type Store struct {3 v int4 }5 6 // Value は値を返す。7 func (s *Store) Value() int { return s.v }8−空行9−// NewStore は Store を生成する。10−func NewStore(v int) *Store { return &Store{v: v} }◀
10行目constructor "NewStore" for struct "Store" should be placed before struct method "Value"
指摘されない
1 // Store は値を保持する。2 type Store struct {3 v int4 }5 6+// NewStore は Store を生成する。7+func NewStore(v int) *Store { return &Store{v: v} }8+空行9 // Value は値を返す。10 func (s *Store) Value() int { return s.v }
funcorder — 関数の並び順を揃える。コンストラクタは型の直後、公開メソッドは非公開メソッドより前、公開関数は非公開関数より前に置く。 設定: function: true
指摘される
1 // Counter は数を数える。2 type Counter struct {3 n int4 }5−空行6−func (c *Counter) reset() { c.n = 0 }◀7 8 // Restart は数え直す。9 func (c *Counter) Restart() { c.reset() }10 11 // Value は数を返す。12 func (c *Counter) Value() int { return c.n }
6行目unexported method "reset" for struct "Counter" should be placed after the exported method "Value"
指摘されない
1 // Counter は数を数える。2 type Counter struct {3 n int4 }5 6 // Restart は数え直す。7 func (c *Counter) Restart() { c.reset() }8 9 // Value は数を返す。10 func (c *Counter) Value() int { return c.n }11+空行12+func (c *Counter) reset() { c.n = 0 }
funcorder — 関数の並び順を揃える。コンストラクタは型の直後、公開メソッドは非公開メソッドより前、公開関数は非公開関数より前に置く。 設定: function: true
指摘される
1 import "strings"2−空行3−func trim(s string) string { return strings.TrimSpace(s) }◀4 5 // CleanName は名前を小文字にして前後の空白を除く。6 func CleanName(s string) string { return strings.ToLower(trim(s)) }
3行目unexported function "trim" should be placed after the exported function "CleanName"
指摘されない
1 import "strings"2 3 // CleanName は名前を小文字にして前後の空白を除く。4 func CleanName(s string) string { return strings.ToLower(trim(s)) }5+空行6+func trim(s string) string { return strings.TrimSpace(s) }
funcorder — 関数の並び順を揃える。コンストラクタは型の直後、公開メソッドは非公開メソッドより前、公開関数は非公開関数より前に置く。 設定: function: true
指摘される
1−import "github.com/google/uuid"◀2 3 // NewID は新しい ID を返す。4−func NewID() string { return uuid.NewString() }
1行目import of package `github.com/google/uuid` is blocked because the module is not in the allowed modules list.
指摘されない
1+import "crypto/rand"2 3 // NewID は新しい ID を返す。4+func NewID() string { return rand.Text() }
gomodguard_v2 — 使ってよい外部モジュールを許可リストで固定する。テンプレートの「外部ライブラリは pgx だけ」を lint で守る。 設定: allowed: [github.com/jackc/pgx/v5]
指摘される
1−// Store はあらゆる永続化操作をまとめた interface。2−type Store interface {◀3− CreateUser()4− UpdateUser()5− DeleteUser()6 FindUser()7− ListUsers()8− CreateOrder()9− UpdateOrder()10− DeleteOrder()11− FindOrder()12− ListOrders()13− Ping()14 }15 16−// HealthCheck は保存先に接続できるかを確かめる。17−func HealthCheck(s Store) { s.Ping() }
2行目the interface has more than 10 methods: 11
iface も同じ箇所を指摘します
指摘されない
1+// UserFinder はユーザーを探す port。2+type UserFinder interface {3 FindUser()4 }5 6+// OrderCreator は注文を作る port。7+type OrderCreator interface {8+ CreateOrder()9+}10+空行11+// Checkout はユーザーを確かめてから注文を作る。12+func Checkout(f UserFinder, c OrderCreator) {13+ f.FindUser()14+ c.CreateOrder()15+}
interfacebloat — メソッドが多すぎる interface を検出する。interface は使う側で小さく定義する。
指摘される
1 module example.com/go-clean2 3 go 1.27.14 5 require github.com/jackc/pgx/v5 v5.7.16−空行7−replace github.com/jackc/pgx/v5 => ../pgx◀
7行目local replacement are not allowed: github.com/jackc/pgx/v5
指摘されない
1 module example.com/go-clean2 3 go 1.27.14 5 require github.com/jackc/pgx/v5 v5.7.1
gomoddirectives — go.mod の replace / retract を禁止する。ローカルの差し替えがテンプレートに残らないようにする。 設定: go-debug-forbidden / toolchain-forbidden / tool-forbidden: true
指摘される
1 module example.com/go-clean2 3 go 1.27.14−空行5−godebug httpmuxgo121=1◀
5行目godebug directive is not allowed
指摘されない
1 module example.com/go-clean2 3 go 1.27.1
gomoddirectives — go.mod の replace / retract を禁止する。ローカルの差し替えがテンプレートに残らないようにする。 設定: go-debug-forbidden / toolchain-forbidden / tool-forbidden: true
指摘される
1 import "fmt"2 3 // Wrap はエラーに文脈を付ける。4 func Wrap(err error) error {5− return fmt.Errorf("find user: %v", err)◀6 }
5行目do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf(\"find user: %v\", err)"
errorlint も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは err113 のメッセージです。
指摘されない
1 import "fmt"2 3 // Wrap はエラーに文脈を付ける。4 func Wrap(err error) error {5+ return fmt.Errorf("find user: %w", err)6 }
errorlint — Go 1.13 以降のエラーラップ(%w)を壊す書き方を検出する。ラップされたエラーは == や型アサーションでは判定できない。
指摘される
1 import "errors"2 3 // ErrNotFound は対象が存在しないことを表す。4 var ErrNotFound = errors.New("not found")5 6 // IsNotFound は err が ErrNotFound かを判定する。7 func IsNotFound(err error) bool {8− return err == ErrNotFound◀9 }
8行目do not compare errors directly "err == ErrNotFound", use "errors.Is(err, ErrNotFound)" instead
errorlint も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは err113 のメッセージです。
指摘されない
1 import "errors"2 3 // ErrNotFound は対象が存在しないことを表す。4 var ErrNotFound = errors.New("not found")5 6 // IsNotFound は err が ErrNotFound かを判定する。7 func IsNotFound(err error) bool {8+ return errors.Is(err, ErrNotFound)9 }
errorlint — Go 1.13 以降のエラーラップ(%w)を壊す書き方を検出する。ラップされたエラーは == や型アサーションでは判定できない。
指摘される
1 // ValidationError は入力値の検証エラー。2 type ValidationError struct {3 Field string4 }5 6 func (e *ValidationError) Error() string { return e.Field + " is invalid" }7 8 // FieldOf は検証エラーの対象フィールドを返す。9 func FieldOf(err error) string {10− if ve, ok := err.(*ValidationError); ok {◀11 return ve.Field12 }13 14 return ""15 }
10行目type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors
指摘されない
1+import "errors"2+空行3 // ValidationError は入力値の検証エラー。4 type ValidationError struct {5 Field string6 }7 8 func (e *ValidationError) Error() string { return e.Field + " is invalid" }9 10 // FieldOf は検証エラーの対象フィールドを返す。11 func FieldOf(err error) string {12+ if ve, ok := errors.AsType[*ValidationError](err); ok {13 return ve.Field14 }15 16 return ""17 }
errorlint — Go 1.13 以降のエラーラップ(%w)を壊す書き方を検出する。ラップされたエラーは == や型アサーションでは判定できない。
指摘される
1 import (2 "encoding/json"3 "io"4 )5 6 // WriteJSON は v を JSON で書き出す。7 func WriteJSON(w io.Writer, v any) {8− json.NewEncoder(w).Encode(v)◀9 }
8行目Error return value of `(*encoding/json.Encoder).Encode` is not checked
指摘されない
1 import (2 "encoding/json"3 "io"4+ "log/slog"5 )6 7 // WriteJSON は v を JSON で書き出す。8 func WriteJSON(w io.Writer, v any) {9+ if err := json.NewEncoder(w).Encode(v); err != nil {10+ slog.Error("write json", "error", err)11+ }12 }
errcheck — 戻り値の error を受け取らずに捨てている呼び出しを検出する。Close / Print 系は既定の除外プリセット(std-error-handling)で対象外。 設定: check-blank: true
指摘される
1 import "strconv"2 3 // ParsePort は文字列をポート番号にする。変換できなければ 0 を返す。4 func ParsePort(s string) int {5− n, _ := strconv.Atoi(s)◀6 7 return n8 }
5行目Error return value of `strconv.Atoi` is not checked
指摘されない
1 import "strconv"2 3 // ParsePort は文字列をポート番号にする。変換できなければ 0 を返す。4 func ParsePort(s string) int {5+ n, err := strconv.Atoi(s)6+ if err != nil {7+ return 08+ }9 10 return n11 }
errcheck — 戻り値の error を受け取らずに捨てている呼び出しを検出する。Close / Print 系は既定の除外プリセット(std-error-handling)で対象外。 設定: check-blank: true
指摘される
1 import "errors"2 3−// NotFound は対象が存在しないことを表す。4−var NotFound = errors.New("not found")◀
4行目the sentinel error name `NotFound` should conform to the `ErrXxx` format
指摘されない
1 import "errors"2 3+// ErrNotFound は対象が存在しないことを表す。4+var ErrNotFound = errors.New("not found")
errname — センチネルエラーは ErrXxx、エラー型は XxxError という名前に揃える。
指摘される
1−// Validation は入力値の検証エラー。2−type Validation struct {◀3 Field string4 }5 6−func (e *Validation) Error() string { return e.Field + " is invalid" }
2行目the error type name `Validation` should conform to the `XxxError` format
指摘されない
1+// ValidationError は入力値の検証エラー。2+type ValidationError struct {3 Field string4 }5 6+func (e *ValidationError) Error() string { return e.Field + " is invalid" }
errname — センチネルエラーは ErrXxx、エラー型は XxxError という名前に揃える。
指摘される
1 import (2 "errors"3 "strings"4 )5 6 // ParseEmail はメールアドレスを検証する。7 func ParseEmail(s string) (string, error) {8 if !strings.Contains(s, "@") {9− return "", errors.New("invalid email")◀10 }11 12 return s, nil13 }
9行目do not define dynamic errors, use wrapped static errors instead: "errors.New(\"invalid email\")"
指摘されない
1 import (2 "errors"3 "strings"4 )5 6+// ErrInvalidEmail はメールアドレスが不正なことを表す。7+var ErrInvalidEmail = errors.New("invalid email")8+空行9 // ParseEmail はメールアドレスを検証する。10 func ParseEmail(s string) (string, error) {11 if !strings.Contains(s, "@") {12+ return "", ErrInvalidEmail13 }14 15 return s, nil16 }
err113 — 関数の中でその場で作るエラー(errors.New / 包まない fmt.Errorf)を禁止し、定義済みのセンチネルエラーに揃える。
指摘される
1−import "strconv"2 3 // ParsePage はページ番号を読む。4 func ParsePage(s string) (int, error) {5− return strconv.Atoi(s)◀6 }
5行目error returned from external package is unwrapped: sig: func strconv.Atoi(s string) (int, error)
指摘されない
1+import (2+ "fmt"3+ "strconv"4+)5 6 // ParsePage はページ番号を読む。7 func ParsePage(s string) (int, error) {8+ n, err := strconv.Atoi(s)9+ if err != nil {10+ return 0, fmt.Errorf("parse page: %w", err)11+ }12+空行13+ return n, nil14 }
wrapcheck — 外部パッケージから返ったエラーを、そのまま返さず %w で文脈を付けて返させる。自モジュール内のエラーは対象外。 設定: ignorePackageGlobs: example.com/go-clean/*
指摘される
1 // User はユーザー。2 type User struct {3 Name string4 }5 6 // Find は名前でユーザーを探す。7 func Find(users []User, name string) (*User, error) {8 for i := range users {9 if users[i].Name == name {10 return &users[i], nil11 }12 }13 14− return nil, nil◀15 }
14行目return both a `nil` error and an invalid value: use a sentinel error instead
指摘されない
1+import "errors"2+空行3+// ErrNotFound は対象が存在しないことを表す。4+var ErrNotFound = errors.New("not found")5+空行6 // User はユーザー。7 type User struct {8 Name string9 }10 11 // Find は名前でユーザーを探す。12 func Find(users []User, name string) (*User, error) {13 for i := range users {14 if users[i].Name == name {15 return &users[i], nil16 }17 }18 19+ return nil, ErrNotFound20 }
nilnil — `return nil, nil` を禁止する。「見つからない」は専用のエラーで表す。 設定: detect-opposite: true
指摘される
1 import "errors"2 3 // ErrEmptyID は ID が空なことを表す。4 var ErrEmptyID = errors.New("empty id")5 6 // User は利用者。7 type User struct {8 ID string9 }10 11 // NewUser は User を生成する。12 func NewUser(id string) (*User, error) {13− u := &User{ID: id}14 if id == "" {15− return u, ErrEmptyID◀16 }17 18− return u, nil19 }
15行目return both a non-nil error and a valid value: use separate returns instead
指摘されない
1 import "errors"2 3 // ErrEmptyID は ID が空なことを表す。4 var ErrEmptyID = errors.New("empty id")5 6 // User は利用者。7 type User struct {8 ID string9 }10 11 // NewUser は User を生成する。12 func NewUser(id string) (*User, error) {13 if id == "" {14+ return nil, ErrEmptyID15 }16 17+ return &User{ID: id}, nil18 }
nilnil — `return nil, nil` を禁止する。「見つからない」は専用のエラーで表す。 設定: detect-opposite: true
指摘される
1−import "strconv"2 3 // ParsePort はポート番号を読む。4 func ParsePort(s string) (int, error) {5 n, err := strconv.Atoi(s)6 if err != nil {7− return 0, nil◀8 }9 10 return n, nil11 }
7行目error is not nil (line 8) but it returns nil
指摘されない
1+import (2+ "fmt"3+ "strconv"4+)5 6 // ParsePort はポート番号を読む。7 func ParsePort(s string) (int, error) {8 n, err := strconv.Atoi(s)9 if err != nil {10+ return 0, fmt.Errorf("parse port: %w", err)11 }12 13 return n, nil14 }
nilerr — err が nil でないのに nil を返している箇所を検出する。
指摘される
1 import "fmt"2 3 // Describe はユーザーの説明文を返す。4 func Describe(name string, age int) string {5− return fmt.Sprintf("%s (%s)", name, age)◀6 }
5行目printf: fmt.Sprintf format %s has arg age of wrong type int
指摘されない
1 import "fmt"2 3 // Describe はユーザーの説明文を返す。4 func Describe(name string, age int) string {5+ return fmt.Sprintf("%s (%d)", name, age)6 }
govet — go vet と同じ解析。printf の書式と引数の不一致、ロックのコピーなど、コンパイルは通るが誤っているコードを検出する。 設定: enable-all: true / disable: [fieldalignment]
指摘される
1 import "sync"2 3 // Counter はスレッドセーフなカウンタ。4 type Counter struct {5 mu sync.Mutex6 n int7 }8 9 // Value は現在値を返す。10−func (c Counter) Value() int {◀11 c.mu.Lock()12 defer c.mu.Unlock()13 14 return c.n15 }
10行目copylocks: Value passes lock by value: example.com/go-clean/internal/cases/gv_copylocks_bad.Counter contains sync.Mutex
指摘されない
1 import "sync"2 3 // Counter はスレッドセーフなカウンタ。4 type Counter struct {5 mu sync.Mutex6 n int7 }8 9 // Value は現在値を返す。10+func (c *Counter) Value() int {11 c.mu.Lock()12 defer c.mu.Unlock()13 14 return c.n15 }
govet — go vet と同じ解析。printf の書式と引数の不一致、ロックのコピーなど、コンパイルは通るが誤っているコードを検出する。 設定: enable-all: true / disable: [fieldalignment]
指摘される
1 import "log/slog"2 3 // LogCreated はユーザー作成をログに出す。4 func LogCreated(id string) {5− slog.Info("user created", "id")◀6 }
5行目slog: call to slog.Info missing a final value
revive も同じ箇所を指摘します
指摘されない
1 import "log/slog"2 3 // LogCreated はユーザー作成をログに出す。4 func LogCreated(id string) {5+ slog.Info("user created", "id", id)6 }
govet — go vet と同じ解析。printf の書式と引数の不一致、ロックのコピーなど、コンパイルは通るが誤っているコードを検出する。 設定: enable-all: true / disable: [fieldalignment]
指摘される
1 import (2 "fmt"3 "strconv"4 )5 6 // Sum は文字列の数値を合計する。7 func Sum(a, b string) (int, error) {8 x, err := strconv.Atoi(a)9 if err != nil {10 return 0, fmt.Errorf("parse a: %w", err)11 }12 13 if b != "" {14− y, err := strconv.Atoi(b)◀15− if err != nil {16− return 0, fmt.Errorf("parse b: %w", err)17 }18 19 x += y20 }21 22− return x, err23 }
14行目shadow: declaration of "err" shadows declaration at line 11
wrapcheck も同じ箇所を指摘します
指摘されない
1 import (2 "fmt"3 "strconv"4 )5 6 // Sum は文字列の数値を合計する。7 func Sum(a, b string) (int, error) {8 x, err := strconv.Atoi(a)9 if err != nil {10 return 0, fmt.Errorf("parse a: %w", err)11 }12 13 if b != "" {14+ y, parseErr := strconv.Atoi(b)15+ if parseErr != nil {16+ return 0, fmt.Errorf("parse b: %w", parseErr)17 }18 19 x += y20 }21 22+ return x, nil23 }
govet — go vet と同じ解析。printf の書式と引数の不一致、ロックのコピーなど、コンパイルは通るが誤っているコードを検出する。 設定: enable-all: true / disable: [fieldalignment]
指摘される
1 import "errors"2 3 // ErrEmpty は値が空なことを表す。4 var ErrEmpty = errors.New("empty")5 6 // Check は値を確かめる。7 func Check(v *int) error {8 if v == nil {9 return ErrEmpty10 }11 12− if v == nil {◀13− return ErrEmpty14− }15−空行16 return nil17 }
12行目nilness: impossible condition: non-nil == nil
指摘されない
1 import "errors"2 3 // ErrEmpty は値が空なことを表す。4 var ErrEmpty = errors.New("empty")5 6 // Check は値を確かめる。7 func Check(v *int) error {8 if v == nil {9 return ErrEmpty10 }11 12 return nil13 }
govet — go vet と同じ解析。printf の書式と引数の不一致、ロックのコピーなど、コンパイルは通るが誤っているコードを検出する。 設定: enable-all: true / disable: [fieldalignment]
staticcheck · バグ検出 · 手で修正 · golangci-lint の既定で有効
context.WithValue のキーに組み込み型を使わない(SA1029)
string のキーは別パッケージのキーと衝突しうる。非公開の専用型をキーにする(repository/tx.go の txKey{} と同じ形)。
指摘される
1 import "context"2 3 // WithRequestID はリクエスト ID を context に入れる。4 func WithRequestID(ctx context.Context, id string) context.Context {5− return context.WithValue(ctx, "request_id", id)◀6 }
5行目SA1029: should not use built-in type string as key for value; define your own type to avoid collisions
指摘されない
1 import "context"2+空行3+type requestIDKey struct{}4 5 // WithRequestID はリクエスト ID を context に入れる。6 func WithRequestID(ctx context.Context, id string) context.Context {7+ return context.WithValue(ctx, requestIDKey{}, id)8 }
staticcheck — staticcheck の SA 系チェック。context のキーや非推奨 API など、実行時に問題になりやすい書き方を検出する。 設定: checks: [all, -ST1000]
staticcheck · バグ検出 · 手で修正 · golangci-lint の既定で有効
副作用のない関数の戻り値を捨てない(SA4017)
strings.TrimSpace は引数を書き換えず、結果を返すだけ。戻り値を使わないと何も起きない。
指摘される
1 import "strings"2 3 // Clean は前後の空白を取り除く。4 func Clean(s string) string {5− strings.TrimSpace(s)◀6−空行7− return s8 }
5行目SA4017: TrimSpace doesn't have side effects and its return value is ignored
指摘されない
1 import "strings"2 3 // Clean は前後の空白を取り除く。4 func Clean(s string) string {5+ return strings.TrimSpace(s)6 }
staticcheck — staticcheck の SA 系チェック。context のキーや非推奨 API など、実行時に問題になりやすい書き方を検出する。 設定: checks: [all, -ST1000]
forcetypeassert · バグ検出 · 手で修正
型アサーションは ok を受け取って確かめる
v.(string) は型が違うと panic する。v, ok := ... で確かめて分岐する。
指摘される
1 // NameOf は値を名前として取り出す。2 func NameOf(v any) string {3− name := v.(string)◀4 5 return name6 }
3行目type assertion must be checked
指摘されない
1 // NameOf は値を名前として取り出す。2 func NameOf(v any) string {3+ name, ok := v.(string)4+ if !ok {5+ return ""6+ }7 8 return name9 }
forcetypeassert — ok を受け取らない型アサーション(失敗すると panic する)を禁止する。
指摘される
1 // Status は注文の状態。2 type Status int3 4 // Status の値。5 const (6 StatusPending Status = iota7 StatusPaid8 StatusShipped9 )10 11 // Label は表示名を返す。12 func Label(s Status) string {13 switch s {◀14 case StatusPending:15 return "pending"16 case StatusPaid:17 return "paid"18 }19 20 return ""21 }
13行目missing cases in switch of type qexhaustivebad.Status: qexhaustivebad.StatusShipped
指摘されない
1 // Status は注文の状態。2 type Status int3 4 // Status の値。5 const (6 StatusPending Status = iota7 StatusPaid8 StatusShipped9 )10 11 // Label は表示名を返す。12 func Label(s Status) string {13 switch s {14 case StatusPending:15 return "pending"16 case StatusPaid:17 return "paid"18+ case StatusShipped:19+ return "shipped"20 }21 22 return ""23 }
exhaustive — 列挙型の switch で、すべての値を扱っているかを検出する。default があれば網羅とみなす。 設定: check: [switch, map] / default-signifies-exhaustive: true
指摘される
1 // Status は注文の状態。2 type Status int3 4 // 注文の状態の一覧。5 const (6 StatusPending Status = iota7 StatusPaid8 StatusShipped9 )10 11 var statusNames = map[Status]string{◀12 StatusPending: "pending",13 StatusPaid: "paid",14 }15 16 // Name は表示名を返す。17 func (s Status) Name() string { return statusNames[s] }
11行目missing keys in map of key type sexmapbad.Status: sexmapbad.StatusShipped
指摘されない
1 // Status は注文の状態。2 type Status int3 4 // 注文の状態の一覧。5 const (6 StatusPending Status = iota7 StatusPaid8 StatusShipped9 )10 11 var statusNames = map[Status]string{12 StatusPending: "pending",13 StatusPaid: "paid",14+ StatusShipped: "shipped",15 }16 17 // Name は表示名を返す。18 func (s Status) Name() string { return statusNames[s] }
exhaustive — 列挙型の switch で、すべての値を扱っているかを検出する。default があれば網羅とみなす。 設定: check: [switch, map] / default-signifies-exhaustive: true
指摘される
1 import (2− "math/rand"3− "strconv"4 )5 6 // NewToken はトークンを作る。7−func NewToken() string {8− return strconv.Itoa(rand.Int())◀9 }
8行目G404: Use of weak random number generator (math/rand or math/rand/v2 instead of crypto/rand)
指摘されない
1 import (2+ "crypto/rand"3+ "encoding/hex"4+ "fmt"5 )6 7+const tokenBytes = 168+空行9 // NewToken はトークンを作る。10+func NewToken() (string, error) {11+ b := make([]byte, tokenBytes)12+ if _, err := rand.Read(b); err != nil {13+ return "", fmt.Errorf("read random: %w", err)14+ }15+空行16+ return hex.EncodeToString(b), nil17 }
gosec — セキュリティ上の問題(弱い乱数、SQL の文字列連結、ファイルパスの扱いなど)を検出する。
指摘される
1 // Counter は数を数える。2 type Counter struct {◀3 n int4 }5 6 // Inc は数を 1 増やす。7 func (c *Counter) Inc() { c.n++ }8 9 // Value は数を返す。10−func (c Counter) Value() int { return c.n }
2行目the methods of "Counter" use pointer receiver and non-pointer receiver.
指摘されない
1 // Counter は数を数える。2 type Counter struct {3 n int4 }5 6 // Inc は数を 1 増やす。7 func (c *Counter) Inc() { c.n++ }8 9 // Value は数を返す。10+func (c *Counter) Value() int { return c.n }
recvcheck — 同じ型のメソッドで、ポインタレシーバと値レシーバを混ぜない。
指摘される
1 import "time"2 3 // Timeout は秒数からタイムアウトを作る。4−func Timeout(seconds time.Duration) time.Duration {5− return seconds * time.Second◀6 }
5行目Multiplication of durations: `seconds * time.Second`
指摘されない
1 import "time"2 3 // Timeout は秒数からタイムアウトを作る。4+func Timeout(seconds int) time.Duration {5+ return time.Duration(seconds) * time.Second6 }
durationcheck — time.Duration どうしの掛け算(単位が二重になるバグ)を検出する。
指摘される
1 import "context"2 3 type idKey struct{}4 5 // Each は ID ごとに処理する。6 func Each(ctx context.Context, ids []string, fn func(context.Context)) {7 for _, id := range ids {8− ctx = context.WithValue(ctx, idKey{}, id)◀9− fn(ctx)10 }11 }
8行目nested context in loop
指摘されない
1 import "context"2 3 type idKey struct{}4 5 // Each は ID ごとに処理する。6 func Each(ctx context.Context, ids []string, fn func(context.Context)) {7 for _, id := range ids {8+ idCtx := context.WithValue(ctx, idKey{}, id)9+ fn(idCtx)10 }11 }
fatcontext — ループの中で context を上書きし続け、入れ子が深くなっていく書き方を検出する。
指摘される
1 import "strings"2 3 // Upper はすべて大文字にする。4 func Upper(names []string) []string {5− out := make([]string, len(names))6 for _, n := range names {7 out = append(out, strings.ToUpper(n))◀8 }9 10 return out11 }
7行目append to slice `out` with non-zero initialized length
指摘されない
1 import "strings"2 3 // Upper はすべて大文字にする。4 func Upper(names []string) []string {5+ out := make([]string, 0, len(names))6 for _, n := range names {7 out = append(out, strings.ToUpper(n))8 }9 10 return out11 }
makezero — 長さを指定して make したスライスに append している箇所(先頭にゼロ値が残るバグ)を検出する。
指摘される
1−import "fmt"2 3 // BaseURL は API の URL を作る。4 func BaseURL(host string, port int) string {5− return fmt.Sprintf("https://%s:%d", host, port)◀6 }
5行目host:port in url should be constructed with net.JoinHostPort and not directly with fmt.Sprintf
指摘されない
1+import (2+ "net"3+ "net/url"4+ "strconv"5+)6 7 // BaseURL は API の URL を作る。8 func BaseURL(host string, port int) string {9+ u := url.URL{Scheme: "https", Host: net.JoinHostPort(host, strconv.Itoa(port))}10+空行11+ return u.String()12 }
nosprintfhostport — Sprintf で host:port を組み立てている箇所を検出する。IPv6 で壊れるので net.JoinHostPort を使う。
指摘される
1 import "net/http"2 3 const maxIdleConns = 104 5−// Setup は HTTP 通信のアイドル接続の上限を設定する。6−func Setup() {7− http.DefaultTransport = &http.Transport{MaxIdleConns: maxIdleConns}◀8 }
7行目reassigning variable DefaultTransport in other package http
指摘されない
1 import "net/http"2 3 const maxIdleConns = 104 5+// NewClient はアイドル接続の上限を設定した HTTP クライアントを作る。6+func NewClient() *http.Client {7+ return &http.Client{Transport: &http.Transport{MaxIdleConns: maxIdleConns}}8 }
reassign — 他パッケージの変数(http.DefaultClient など)を書き換えている箇所を検出する。既定では Err* と EOF だけが対象なので、すべての変数に広げる。 設定: patterns: [".*"]
指摘される
1 // User はユーザー。2 type User struct {3 name string4 email string5 }6 7 // Name は名前を返す。8 func (u *User) Name() string { return u.name }9 10 // Email はメールアドレスを返す。11−func (usr *User) Email() string { return usr.email }◀
11行目receiver-naming: receiver name usr is longer than 2 characters
指摘されない
1 // User はユーザー。2 type User struct {3 name string4 email string5 }6 7 // Name は名前を返す。8 func (u *User) Name() string { return u.name }9 10 // Email はメールアドレスを返す。11+func (u *User) Email() string { return u.email }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Path はユーザーの URL パスを返す。2−func Path(userId string) string {◀3− return "/users/" + userId4 }
2行目var-naming: func parameter userId should be userID
指摘されない
1 // Path はユーザーの URL パスを返す。2+func Path(userID string) string {3+ return "/users/" + userID4 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Counts は空の集計表を返す。2 func Counts() map[string]int {3− return make(map[string]int)◀4 }
3行目enforce-map-style: use map[type]type{} instead of make(map[type]type)
指摘されない
1 // Counts は空の集計表を返す。2 func Counts() map[string]int {3+ return map[string]int{}4 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Payload は任意の値を包む。2 type Payload struct {3− Data interface{}◀4 }
3行目use-any: since Go 1.18 'interface{}' can be replaced by 'any'
指摘されない
1 // Payload は任意の値を包む。2 type Payload struct {3+ Data any4 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Label は表示名を返す。2 func Label(name string) string {3 if name == "" {4 return "guest"5− } else {◀6− return name7 }8 }
5行目indent-error-flow: if block ends with a return statement, so drop this else and outdent its block
指摘されない
1 // Label は表示名を返す。2 func Label(name string) string {3 if name == "" {4 return "guest"5 }6+空行7+ return name8 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "strings"2 3 // Normalize は名前を正規化する。4 func Normalize(name string, ok bool) string {5− var result string6− if ok {◀7− result = strings.ToLower(strings.TrimSpace(name))8− } else {9 return ""10 }11 12− return result13 }
6行目early-return: if c { ... } else { ... return } can be simplified to if !c { ... return } ...
指摘されない
1 import "strings"2 3 // Normalize は名前を正規化する。4 func Normalize(name string, ok bool) string {5+ if !ok {6 return ""7 }8 9+ return strings.ToLower(strings.TrimSpace(name))10 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "context"3 "log/slog"4 )5 6 // Find はユーザーを探す。7−func Find(id string, ctx context.Context) {◀8 slog.InfoContext(ctx, "find user", "user_id", id)9 }
7行目context-as-argument: context.Context should be the first parameter of a function
指摘されない
1 import (2 "context"3 "log/slog"4 )5 6 // Find はユーザーを探す。7+func Find(ctx context.Context, id string) {8 slog.InfoContext(ctx, "find user", "user_id", id)9 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Next は次の番号を返す。2 func Next(n int) int {3− n += 1◀4 5 return n6 }
3行目increment-decrement: should replace n += 1 with n++
指摘されない
1 // Next は次の番号を返す。2 func Next(n int) int {3+ n++4 5 return n6 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // UserRepository は users テーブルを扱う。2 type UserRepository struct{}3 4 func NewUserRepository() *UserRepository {◀5 return &UserRepository{}6 }
4行目exported: exported function NewUserRepository should have comment or be unexported
指摘されない
1 // UserRepository は users テーブルを扱う。2 type UserRepository struct{}3 4+// NewUserRepository は UserRepository を生成する。5 func NewUserRepository() *UserRepository {6 return &UserRepository{}7 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "context"2 3 // StubUserRepository はテスト用に、常に「存在しない」と答える。4 type StubUserRepository struct{}5 6 // ExistsByEmail は常に false を返す。7−func (StubUserRepository) ExistsByEmail(ctx context.Context, email string) (bool, error) {◀8 return false, nil9 }
7行目unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _
指摘されない
1 import "context"2 3 // StubUserRepository はテスト用に、常に「存在しない」と答える。4 type StubUserRepository struct{}5 6 // ExistsByEmail は常に false を返す。7+func (StubUserRepository) ExistsByEmail(_ context.Context, _ string) (bool, error) {8 return false, nil9 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Health はヘルスチェック。2 type Health struct{}3 4 // Status は状態を返す。5−func (h *Health) Status() string {◀6 return "ok"7 }
5行目unused-receiver: method receiver 'h' is not referenced in method's body, consider removing or renaming it as _
指摘されない
1 // Health はヘルスチェック。2 type Health struct{}3 4 // Status は状態を返す。5+func (*Health) Status() string {6 return "ok"7 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // SaveAll は保存処理を実行する。2 func SaveAll(save func() error) error {3− if err := save(); err != nil {◀4− return err5− }6−空行7− return nil8 }
3行目if-return: redundant if ...; err != nil check, just return error instead.
指摘されない
1 // SaveAll は保存処理を実行する。2 func SaveAll(save func() error) error {3+ return save()4 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Label は役割の表示名を返す。2 func Label(role string) string {3 label := "Member"4 5 switch role {6 case "admin":7 label = "Administrator"8− break◀9 case "owner":10 label = "Owner"11 }12 13 return label14 }
8行目unnecessary-stmt: omit unnecessary break at the end of case clause
指摘されない
1 // Label は役割の表示名を返す。2 func Label(role string) string {3 label := "Member"4 5 switch role {6 case "admin":7 label = "Administrator"8 case "owner":9 label = "Owner"10 }11 12 return label13 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2− "log/slog"3− "os"4 "strconv"5 )6 7−// MustPort は文字列をポート番号に変換する。変換できなければ終了する。8−func MustPort(s string) int {9 n, err := strconv.Atoi(s)10 if err != nil {11− slog.Error("invalid port", "value", s)12− os.Exit(1)◀13 }14 15− return n16 }
12行目deep-exit: calls to os.Exit only in main() or init() functions
指摘されない
1 import (2+ "fmt"3 "strconv"4 )5 6+// Port は文字列をポート番号に変換する。7+func Port(s string) (int, error) {8 n, err := strconv.Atoi(s)9 if err != nil {10+ return 0, fmt.Errorf("parse port %q: %w", s, err)11 }12 13+ return n, nil14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−// cache は簡易キャッシュ。2−type cache struct {3 items map[string]string4 }5 6 // NewCache はキャッシュを作る。7−func NewCache() *cache {◀8− return &cache{items: map[string]string{}}9 }10 11 // Get は値を返す。12−func (c *cache) Get(key string) string { return c.items[key] }
7行目unexported-return: exported func NewCache returns unexported type *qrvunexpretbad.cache, which can be annoying to use
指摘されない
1+// Cache は簡易キャッシュ。2+type Cache struct {3 items map[string]string4 }5 6 // NewCache はキャッシュを作る。7+func NewCache() *Cache {8+ return &Cache{items: map[string]string{}}9 }10 11 // Get は値を返す。12+func (c *Cache) Get(key string) string { return c.items[key] }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Count は件数の初期値。2−var Count int = 0◀
2行目var-declaration: should drop = 0 from declaration of var Count; it is the zero value
指摘されない
1 // Count は件数の初期値。2+var Count int
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−// Drain はチャネルを読み切る。2 func Drain(ch <-chan error) int {3 n := 04 5 for err := range ch {6 if err != nil {◀7 }8−空行9− n++10 }11 12 return n13 }
6行目empty-block: this block is empty, you can remove it
指摘されない
1+// Drain はチャネルを読み切り、エラーの件数を返す。2 func Drain(ch <-chan error) int {3 n := 04 5 for err := range ch {6 if err != nil {7+ n++8 }9 }10 11 return n12 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "fmt"3 "strconv"4 )5 6 // ParseAge は年齢を読む。7−func ParseAge(s string) (error, int) {◀8 n, err := strconv.Atoi(s)9 if err != nil {10− return fmt.Errorf("parse age: %w", err), 011 }12 13− return nil, n14 }
7行目error-return: error should be the last type when returning multiple items
指摘されない
1 import (2 "fmt"3 "strconv"4 )5 6 // ParseAge は年齢を読む。7+func ParseAge(s string) (int, error) {8 n, err := strconv.Atoi(s)9 if err != nil {10+ return 0, fmt.Errorf("parse age: %w", err)11 }12 13+ return n, nil14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "time"2 3−// DefaultTimeoutSecs は既定のタイムアウト。4−var DefaultTimeoutSecs = 3 * time.Second◀
4行目ST1011: var DefaultTimeoutSecs is of type time.Duration; don't use unit-specific suffix "Secs"
revive も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは staticcheck のメッセージです。
指摘されない
1 import "time"2 3+// DefaultTimeout は既定のタイムアウト。4+var DefaultTimeout = 3 * time.Second
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Register はユーザーを登録する。2−func Register(name, email, phone, city, zip, country string) string {◀3− return name + email + phone + city + zip + country4 }
2行目argument-limit: maximum number of arguments per function exceeded; max 5 but got 6
指摘されない
1+// RegisterInput はユーザー登録の入力。2+type RegisterInput struct {3+ Name string4+ Email string5+ Phone string6+ City string7+ Zip string8+ Country string9+}10+空行11 // Register はユーザーを登録する。12+func Register(in RegisterInput) string {13+ return in.Name + in.Email + in.Phone + in.City + in.Zip + in.Country14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "strings"2 3 // Split は氏名を分ける。4−func Split(full string) (string, string, string, bool) {◀5 first, rest, ok := strings.Cut(full, " ")6 middle, last, _ := strings.Cut(rest, " ")7 8− return first, middle, last, ok9 }
4行目function-result-limit: maximum number of return results per function exceeded; max 3 but got 4
指摘されない
1 import "strings"2 3+// Name は分けた氏名。4+type Name struct {5+ First string6+ Middle string7+ Last string8+}9+空行10 // Split は氏名を分ける。11+func Split(full string) (Name, bool) {12 first, rest, ok := strings.Cut(full, " ")13 middle, last, _ := strings.Cut(rest, " ")14 15+ return Name{First: first, Middle: middle, Last: last}, ok16 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
revive · 命名・書き方 · 手で修正
bool を true / false と比較しない(bool-literal-in-expr)
ok == true は ok と同じ。
指摘される
1 // Label は表示名を返す。2 func Label(active bool) string {3− if active == true {◀4 return "enabled"5 }6 7 return "disabled"8 }
3行目bool-literal-in-expr: omit Boolean literal in expression
指摘されない
1 // Label は表示名を返す。2 func Label(active bool) string {3+ if active {4 return "enabled"5 }6 7 return "disabled"8 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "fmt"3 "time"4− _ "time/tzdata"◀5 )6 7 // Tokyo は東京のタイムゾーンを返す。8 func Tokyo() (*time.Location, error) {9 loc, err := time.LoadLocation("Asia/Tokyo")10 if err != nil {11 return nil, fmt.Errorf("load location: %w", err)12 }13 14 return loc, nil15 }
4行目blank-imports: a blank import should be only in a main or test package, or have a comment justifying it
指摘されない
1 import (2 "fmt"3 "time"4+ _ "time/tzdata" // OS にタイムゾーン情報がない環境でも読み込めるようにする5 )6 7 // Tokyo は東京のタイムゾーンを返す。8 func Tokyo() (*time.Location, error) {9 loc, err := time.LoadLocation("Asia/Tokyo")10 if err != nil {11 return nil, fmt.Errorf("load location: %w", err)12 }13 14 return loc, nil15 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // User はユーザー。2 type User struct {3 first string4 last string5 }6 7 // Name は表示名を返す。8 func (u *User) Name() string {9− return u.name(" ")10 }11 12−func (u *User) name(sep string) string {◀13 return u.first + sep + u.last14 }
12行目confusing-naming: Method 'name' differs only by capitalization to method 'Name' in the same source file
指摘されない
1 // User はユーザー。2 type User struct {3 first string4 last string5 }6 7 // Name は表示名を返す。8 func (u *User) Name() string {9+ return u.joinName(" ")10 }11 12+func (u *User) joinName(sep string) string {13 return u.first + sep + u.last14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Order は注文。2 type Order struct {3 ID string4− Address struct {◀5− City string6− Zip string7− }8 }
4行目nested-structs: no nested structs are allowed
指摘されない
1+// Address は配送先。2+type Address struct {3+ City string4+ Zip string5+}6+空行7 // Order は注文。8 type Order struct {9 ID string10+ Address Address11 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "time"2 3 // Same は同じ時刻かを返す。4 func Same(a, b time.Time) bool {5− return a == b◀6 }
5行目QF1009: probably want to use time.Time.Equal instead
revive も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは staticcheck のメッセージです。
指摘されない
1 import "time"2 3 // Same は同じ時刻かを返す。4 func Same(a, b time.Time) bool {5+ return a.Equal(b)6 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Name は名前。2 type Name string3 4 // String は文字列にする。5 func (n Name) String() string {6− return n.String()◀7 }
6行目unconditional-recursion: unconditional recursive call
指摘されない
1 // Name は名前。2 type Name string3 4 // String は文字列にする。5 func (n Name) String() string {6+ return string(n)7 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−// ファイル: internal/util/util.go2−package util◀3 4 import "strings"5 6−// Slug は URL 用の文字列にする。7−func Slug(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
2行目package-naming: don't use "util" because it is a bad package name according to https://go.dev/blog/package-names#bad-package-names
指摘されない
1+// ファイル: internal/slug/slug.go2+package slug3 4 import "strings"5 6+// Make は URL 用の文字列にする。7+func Make(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // ファイル: internal/order/order.go2−package orders◀3 4 // Total は合計金額を返す。5 func Total(prices []int) int {6 sum := 07 for _, p := range prices {8 sum += p9 }10 11 return sum12 }
2行目package-directory-mismatch: package name "orders" does not match directory name "order"
指摘されない
1 // ファイル: internal/order/order.go2+package order3 4 // Total は合計金額を返す。5 func Total(prices []int) int {6 sum := 07 for _, p := range prices {8 sum += p9 }10 11 return sum12 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−// ファイル名: OrderItem.go2 3 // OrderItemUsecase は注文明細のユースケース。4 type OrderItemUsecase struct{}
-1行目filename-format: Filename OrderItem.go is not of the format ^[_a-z][_a-z0-9]*\.go$.
指摘されない
1+// ファイル名: order_item.go2 3 // OrderItemUsecase は注文明細のユースケース。4 type OrderItemUsecase struct{}
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Sum は合計を返す。2 func Sum(nums []int) int {3− Total := 0◀4 for _, n := range nums {5− Total += n6 }7 8− return Total9 }
3行目unexported-naming: the symbol Total is local, its name should start with a lowercase letter
指摘されない
1 // Sum は合計を返す。2 func Sum(nums []int) int {3+ total := 04 for _, n := range nums {5+ total += n6 }7 8+ return total9 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Cache はキャッシュ。2 type Cache struct {3 items map[string]string4 }5 6−// GetItems は中身を空にし直す。7−func (c *Cache) GetItems() { c.items = map[string]string{} }◀8−空行9 // Len は件数を返す。10 func (c *Cache) Len() int { return len(c.items) }
7行目get-return: function 'GetItems' seems to be a getter but it does not return any result
指摘されない
1 // Cache はキャッシュ。2 type Cache struct {3 items map[string]string4 }5 6 // Len は件数を返す。7 func (c *Cache) Len() int { return len(c.items) }8+空行9+// Reset は中身を空にし直す。10+func (c *Cache) Reset() { c.items = map[string]string{} }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2− userDomain "example.com/go-clean/internal/domain/user"◀3 )4 5 // DefaultName は既定の名前を返す。6−func DefaultName() string { return userDomain.DefaultName }
2行目import-alias-naming: import name (userDomain) must match the regular expression: ^[a-z][a-z0-9]{0,}$
指摘されない
1 import (2+ domainuser "example.com/go-clean/internal/domain/user"3 )4 5 // DefaultName は既定の名前を返す。6+func DefaultName() string { return domainuser.DefaultName }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "strconv"3 "strings"4 )5 6 // ParsePort は文字列をポート番号にする。変換できなければ 0 を返す。7 func ParsePort(s string) int {8− if n, err := strconv.Atoi(◀9− strings.TrimSpace(s),10− ); err == nil {11− return n12 }13 14− return 015 }
8行目multiline-if-init: if-init statement should not span multiple lines
指摘されない
1 import (2 "strconv"3 "strings"4 )5 6 // ParsePort は文字列をポート番号にする。変換できなければ 0 を返す。7 func ParsePort(s string) int {8+ n, err := strconv.Atoi(strings.TrimSpace(s))9+ if err != nil {10+ return 011 }12 13+ return n14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Counter は数を数える。2 type Counter struct {3 n int4 }5 6 // Value は数を返す。7 func (c *Counter) Value() int { return c.n }8 9 // Reset は数を 0 に戻す。10−func (c Counter) Reset() { c.n = 0 }◀
10行目modifies-value-receiver: suspicious assignment to a by-value method receiver
recvcheck も同じ箇所を指摘します
指摘されない
1 // Counter は数を数える。2 type Counter struct {3 n int4 }5 6 // Value は数を返す。7 func (c *Counter) Value() int { return c.n }8 9 // Reset は数を 0 に戻す。10+func (c *Counter) Reset() { c.n = 0 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 const (2 gradeA = 803 gradeB = 604 )5 6 // Grade は点数の評価を返す。7 func Grade(score int) string {8 grade := "C"9 if score >= gradeA {10 grade = "A"11− } else if score >= gradeA {◀12 grade = "B"13 }14 15 return grade16 }
11行目identical-ifelseif-conditions: "if...else if" chain with identical conditions (lines 12 and 14)
指摘されない
1 const (2 gradeA = 803 gradeB = 604 )5 6 // Grade は点数の評価を返す。7 func Grade(score int) string {8 grade := "C"9 if score >= gradeA {10 grade = "A"11+ } else if score >= gradeB {12 grade = "B"13 }14 15 return grade16 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 const (2 gradeA = 803 gradeB = 604 )5 6 // Grade は点数の評価を返す。7 func Grade(score int) string {8 switch {9 case score >= gradeA:10 return "A"11− case score >= gradeA:◀12 return "B"13 default:14 return "C"15 }16 }
11行目identical-switch-conditions: case clause at line 12 has the same condition
指摘されない
1 const (2 gradeA = 803 gradeB = 604 )5 6 // Grade は点数の評価を返す。7 func Grade(score int) string {8 switch {9 case score >= gradeA:10 return "A"11+ case score >= gradeB:12 return "B"13 default:14 return "C"15 }16 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // HasUser は users に id が含まれるかを返す。2 func HasUser(users map[string]string, id string) bool {3− for key := range users {◀4− if key == id {5− return true6− }7− }8 9− return false10 }
3行目inefficient-map-lookup: inefficient lookup of map key
指摘されない
1 // HasUser は users に id が含まれるかを返す。2 func HasUser(users map[string]string, id string) bool {3+ _, ok := users[id]4 5+ return ok6 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // IsAdult は 18 歳以上かを返す。2 func IsAdult(age int) bool {3 const adultAge = 184 5− var adult bool6− if age >= adultAge {◀7− adult = true8− } else {9− adult = false10− }11−空行12− return adult13 }
6行目unnecessary-if: replace this conditional by: adult = age >= adultAge
指摘されない
1 // IsAdult は 18 歳以上かを返す。2 func IsAdult(age int) bool {3 const adultAge = 184 5+ return age >= adultAge6 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // SizeLabel はサイズの表示名を返す。2 func SizeLabel(size string) string {3 switch size {4− case "xs":5− fallthrough◀6− case "s":7 return "small"8 case "l":9 return "large"10 default:11 return "medium"12 }13 }
5行目useless-fallthrough: this "fallthrough" can be removed by consolidating this case clause with the next one
指摘されない
1 // SizeLabel はサイズの表示名を返す。2 func SizeLabel(size string) string {3 switch size {4+ case "xs", "s":5 return "small"6 case "l":7 return "large"8 default:9 return "medium"10 }11 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "time"2 3 // EndOfYear は 2026 年の最終日を返す。4 func EndOfYear() time.Time {5− return time.Date(2026, 13, 0, 0, 0, 0, 0, time.UTC)◀6 }
5行目time-date: time.Date month argument should be between 1 and 12: 13
指摘されない
1 import "time"2 3 // EndOfYear は 2026 年の最終日を返す。4 func EndOfYear() time.Time {5+ return time.Date(2026, time.December, 31, 0, 0, 0, 0, time.UTC)6 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // UserResponse はユーザーの応答。2 type UserResponse struct {3 Name string `json:"name"`4− Nickname string `json:"nickname,omitempy"`◀5 }
4行目struct-tag: unknown option "omitempy" in json tag
指摘されない
1 // UserResponse はユーザーの応答。2 type UserResponse struct {3 Name string `json:"name"`4+ Nickname string `json:"nickname,omitempty"`5 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "sync"2 3 // RunAll は fns を並行に実行し、すべて終わるまで待つ。4 func RunAll(fns []func()) {5 var wg sync.WaitGroup6 7 for _, fn := range fns {8− wg.Go(func() {9− defer wg.Done()◀10−空行11− fn()12− })13 }14 15 wg.Wait()16 }
9行目forbidden-call-in-wg-go: do not call wg.Done inside wg.Go
指摘されない
1 import "sync"2 3 // RunAll は fns を並行に実行し、すべて終わるまで待つ。4 func RunAll(fns []func()) {5 var wg sync.WaitGroup6 7 for _, fn := range fns {8+ wg.Go(fn)9 }10 11 wg.Wait()12 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "net/http"2 3 type statusRecorder struct {4 http.ResponseWriter5 6 status int7 }8 9 // Wrap はステータスコードを記録する ResponseWriter を返す。10 func Wrap(w http.ResponseWriter) http.ResponseWriter {11 return &statusRecorder{ResponseWriter: w, status: http.StatusOK}12 }13 14 // Status は記録したステータスコードを返す。15 func (r *statusRecorder) Status() int { return r.status }16 17 func (r *statusRecorder) WriteHeader(status int) {◀18 r.status = status19 r.ResponseWriter.WriteHeader(status)20 }
17行目exported: exported method statusRecorder.WriteHeader should have comment or be unexported
指摘されない
1 import "net/http"2 3 type statusRecorder struct {4 http.ResponseWriter5 6 status int7 }8 9 // Wrap はステータスコードを記録する ResponseWriter を返す。10 func Wrap(w http.ResponseWriter) http.ResponseWriter {11 return &statusRecorder{ResponseWriter: w, status: http.StatusOK}12 }13 14 // Status は記録したステータスコードを返す。15 func (r *statusRecorder) Status() int { return r.status }16 17+// WriteHeader はステータスコードを記録してから書き込む。18 func (r *statusRecorder) WriteHeader(status int) {19 r.status = status20 r.ResponseWriter.WriteHeader(status)21 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Store は値を保持する。2 type Store struct {3 v int4 }5 6 // Value は値を返す。7−func (store *Store) Value() int { return store.v }◀
7行目receiver-naming: receiver name store is longer than 2 characters
指摘されない
1 // Store は値を保持する。2 type Store struct {3 v int4 }5 6 // Value は値を返す。7+func (s *Store) Value() int { return s.v }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // User は利用者。2 type User struct {3 Email string4 Active bool5 }6 7 // Notify は有効なユーザーにだけ通知する。8 func Notify(u User, send func(email string)) {9− if u.Active {◀10− send(u.Email)11− send(u.Email + ".cc")12− send(u.Email + ".bcc")13 }14 }
9行目early-return: if c { ... } can be rewritten if !c { return } ... to reduce nesting
指摘されない
1 // User は利用者。2 type User struct {3 Email string4 Active bool5 }6 7 // Notify は有効なユーザーにだけ通知する。8 func Notify(u User, send func(email string)) {9+ if !u.Active {10+ return11 }12+空行13+ send(u.Email)14+ send(u.Email + ".cc")15+ send(u.Email + ".bcc")16 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "log/slog"2 3 // SafeRun は fn を実行し、panic を記録する。4 func SafeRun(fn func()) {5 fn()6−空行7− if r := recover(); r != nil {◀8− slog.Error("panic recovered", "panic", r)9− }10 }
7行目defer: recover must be called inside a deferred function
指摘されない
1 import "log/slog"2 3 // SafeRun は fn を実行し、panic を記録する。4 func SafeRun(fn func()) {5+ defer func() {6+ if r := recover(); r != nil {7+ slog.Error("panic recovered", "panic", r)8+ }9+ }()10+空行11 fn()12 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 const (2 standardFee = 5003 remoteFee = 15004 )5 6 // Fee は地域ごとの送料を返す。7 func Fee(region string) int {8 fee := standardFee9− if region == "okinawa" {◀10− fee = remoteFee11− } else if region == "hokkaido" {12 fee = remoteFee13 }14 15 return fee16 }
9行目identical-ifelseif-branches: "if...else if" chain with identical branches (lines 12 and 14)
指摘されない
1 const (2 standardFee = 5003 remoteFee = 15004 )5 6 // Fee は地域ごとの送料を返す。7 func Fee(region string) int {8 fee := standardFee9+ if region == "okinawa" || region == "hokkaido" {10 fee = remoteFee11 }12 13 return fee14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 const (2 standardFee = 5003 remoteFee = 15004 )5 6 // Fee は地域ごとの送料を返す。7 func Fee(region string) int {8 switch region {◀9− case "okinawa":10− return remoteFee11− case "hokkaido":12 return remoteFee13 default:14 return standardFee15 }16 }
8行目identical-switch-branches: "switch" with identical branches (lines 12 and 14)
指摘されない
1 const (2 standardFee = 5003 remoteFee = 15004 )5 6 // Fee は地域ごとの送料を返す。7 func Fee(region string) int {8 switch region {9+ case "okinawa", "hokkaido":10 return remoteFee11 default:12 return standardFee13 }14 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "encoding/json"3 "fmt"4 )5 6 // Money は金額。7 type Money struct {8 yen int9 }10 11 // MarshalJSON は円の数値として出力する。12−func (m *Money) MarshalJSON() ([]byte, error) {◀13 b, err := json.Marshal(m.yen)14 if err != nil {15 return nil, fmt.Errorf("marshal money: %w", err)16 }17 18 return b, nil19 }
12行目marshal-receiver: Money.MarshalJSON method should use a value receiver, not a pointer receiver
指摘されない
1 import (2 "encoding/json"3 "fmt"4 )5 6 // Money は金額。7 type Money struct {8 yen int9 }10 11 // MarshalJSON は円の数値として出力する。12+func (m Money) MarshalJSON() ([]byte, error) {13 b, err := json.Marshal(m.yen)14 if err != nil {15 return nil, fmt.Errorf("marshal money: %w", err)16 }17 18 return b, nil19 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−import "sort"2 3 // SortNames は名前を昇順に並べる。4−func SortNames(names []string) { sort.Strings(names) }◀
4行目use-slices-sort: replace sort.Strings by slices.Sort
指摘されない
1+import "slices"2 3 // SortNames は名前を昇順に並べる。4+func SortNames(names []string) { slices.Sort(names) }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // Merge は 2 つのタグ一覧をつなげた新しいスライスを返す。2−func Merge(a, b []string) []string { return append(append([]string{}, a...), b...) }◀
2行目use-slices-concat: replace nested appends by a call to slices.Concat
指摘されない
1+import "slices"2+空行3 // Merge は 2 つのタグ一覧をつなげた新しいスライスを返す。4+func Merge(a, b []string) []string { return slices.Concat(a, b) }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // APIBase は外部 API の URL。2−const APIBase = "http://api.example.com/v1"◀
2行目unsecure-url-scheme: prefer secure protocol https over http in "http://api.example.com/v1"
指摘されない
1 // APIBase は外部 API の URL。2+const APIBase = "https://api.example.com/v1"
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 // EmptyTags は空のタグ一覧を返す。2−func EmptyTags() []string { return make([]string, 0) }◀
2行目enforce-slice-style: use []type{} instead of make([]type, 0) (or declare nil slice)
指摘されない
1 // EmptyTags は空のタグ一覧を返す。2+func EmptyTags() []string { return []string{} }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import (2 "log/slog"3− "os"4 "testing"5 )6 7 func TestMain(m *testing.M) {8 slog.SetDefault(slog.New(slog.DiscardHandler))9 10− os.Exit(m.Run())◀11 }
10行目redundant-test-main-exit: redundant call to os.Exit in TestMain function, the test runner will handle it automatically as of Go 1.15
指摘されない
1 import (2 "log/slog"3 "testing"4 )5 6 func TestMain(m *testing.M) {7 slog.SetDefault(slog.New(slog.DiscardHandler))8 9+ m.Run()10 }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1−import "runtime"2−空行3 // Cache はキャッシュ。4 type Cache struct {5 items map[string]string6 }7 8 // Clear は中身を空にする。9 func (c *Cache) Clear() {10 c.items = map[string]string{}11−空行12− runtime.GC()◀13 }14 15 // Len は件数を返す。16 func (c *Cache) Len() int { return len(c.items) }
12行目call-to-gc: explicit call to the garbage collector
指摘されない
1 // Cache はキャッシュ。2 type Cache struct {3 items map[string]string4 }5 6 // Clear は中身を空にする。7 func (c *Cache) Clear() {8 c.items = map[string]string{}9 }10 11 // Len は件数を返す。12 func (c *Cache) Len() int { return len(c.items) }
revive — golint の後継。ルールを 1 つずつ選んで有効にし、名前・書き方・ドキュメントコメントを揃える。公開識別子のコメントは golangci-lint の既定除外を解除して必須にしている。 設定: rules: argument-limit(5), blank-imports, bool-literal-in-expr, call-to-gc, confusing-naming, context-as-argument, deep-exit, defer, early-return(allow-jump), empty-block, enforce-map-style(literal), enforce-slice-style(literal), error-return, exported(check-private-receivers), filename-format(^[_a-z][_a-z0-9]*\.go$), forbidden-call-in-wg-go, function-result-limit(3), get-return, identical-ifelseif-branches, identical-ifelseif-conditions, identical-switch-branches, identical-switch-conditions, if-return, import-alias-naming, increment-decrement, indent-error-flow, inefficient-map-lookup, marshal-receiver, modifies-value-receiver, multiline-if-init, nested-structs, package-directory-mismatch, package-naming, receiver-naming(max-length: 2), redundant-import-alias, redundant-test-main-exit, struct-tag, superfluous-else, time-date, time-equal, time-naming, unconditional-recursion, unexported-naming, unexported-return, unnecessary-if, unnecessary-stmt, unsecure-url-scheme, unused-parameter, unused-receiver, use-any, use-slices-concat, use-slices-sort, useless-fallthrough, var-declaration, var-naming
指摘される
1 import "errors"2 3 // ErrNotFound は対象が存在しないことを表す。4−var ErrNotFound = errors.New("User not found.")◀
4行目ST1005: error strings should not end with punctuation or newlines
指摘されない
1 import "errors"2 3 // ErrNotFound は対象が存在しないことを表す。4+var ErrNotFound = errors.New("user not found")
staticcheck(ST 系) — staticcheck の ST 系チェック(v1 の stylecheck。v2 で staticcheck に統合された)。エラーメッセージの書き方や、ID / URL などの略語の表記を揃える。パッケージコメント(ST1000)は必須にしない。 設定: checks: [all, -ST1000]
指摘される
1 // Sum は合計を返す。2 func Sum(nums []int) int {3 total := 04 for _, n := range nums {5− total = total + n◀6 }7 8 return total9 }
5行目assignOp: replace `total = total + n` with `total += n`
指摘されない
1 // Sum は合計を返す。2 func Sum(nums []int) int {3 total := 04 for _, n := range nums {5+ total += n6 }7 8 return total9 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // 評価の境界となる点数。2 const (3 GradeA = 804 GradeB = 605 )6 7 // Grade は点数から評価を返す。8 func Grade(score int) string {9− if score >= GradeA {◀10 return "A"11− } else if score >= GradeB {12 return "B"13− } else {14 return "C"15 }16 }
9行目ifElseChain: rewrite if-else to switch statement
revive も同じ箇所を指摘します
指摘されない
1 // 評価の境界となる点数。2 const (3 GradeA = 804 GradeB = 605 )6 7 // Grade は点数から評価を返す。8 func Grade(score int) string {9+ switch {10+ case score >= GradeA:11 return "A"12+ case score >= GradeB:13 return "B"14+ default:15 return "C"16 }17 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // Head は先頭から指定した個数だけ返す。2−func Head(nums []int, len int) []int {◀3− return nums[:len]4 }
2行目builtinShadow: shadowing of predeclared identifier: len
指摘されない
1 // Head は先頭から指定した個数だけ返す。2+func Head(nums []int, count int) []int {3+ return nums[:count]4 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // Clone は複製を返す。2 func Clone(src []int) []int {3 dst := make([]int, len(src))4− copy(dst, dst)◀5 6 return dst7 }
4行目dupArg: suspicious duplicated args in copy(dst, dst)
指摘されない
1 // Clone は複製を返す。2 func Clone(src []int) []int {3 dst := make([]int, len(src))4+ copy(dst, src)5 6 return dst7 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // Prefix は表示用の接頭辞を返す。2−func Prefix(admin bool) string {3− if admin {◀4− return "user: "5− } else {6− return "user: "7− }8 }
3行目dupBranchBody: both branches in if statement have same body
revive も同じ箇所を指摘します
指摘されない
1 // Prefix は表示用の接頭辞を返す。2+func Prefix() string {3+ return "user: "4 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1−import "io"2 3−// CloseAll はすべて閉じる。4−func CloseAll(closers []io.Closer) {5 for _, c := range closers {6− defer c.Close()◀7 }8 }
6行目defer: prefer not to defer inside loops
gocritic も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは revive のメッセージです。
指摘されない
1+import (2+ "errors"3+ "io"4+)5 6+// CloseAll はすべて閉じ、失敗したものをまとめて返す。7+func CloseAll(closers []io.Closer) error {8+ errs := make([]error, 0, len(closers))9+空行10 for _, c := range closers {11+ errs = append(errs, c.Close())12 }13+空行14+ return errors.Join(errs...)15 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 import "strings"2 3 // SameEmail は大文字小文字を無視してメールアドレスを比べる。4−func SameEmail(a, b string) bool { return strings.ToLower(a) == strings.ToLower(b) }◀
4行目equalFold: consider replacing with strings.EqualFold(a, b)
指摘されない
1 import "strings"2 3 // SameEmail は大文字小文字を無視してメールアドレスを比べる。4+func SameEmail(a, b string) bool { return strings.EqualFold(a, b) }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // WithDefaults は既定のタグを足す。2 func WithDefaults(tags []string) []string {3− tags = append(tags, "go")◀4− tags = append(tags, "api")5−空行6− return tags7 }
3行目appendCombine: can combine chain of 2 appends into one
指摘されない
1 // WithDefaults は既定のタグを足す。2 func WithDefaults(tags []string) []string {3+ return append(tags, "go", "api")4 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 import (2 "fmt"3 "io"4 )5 6 // Greet は挨拶を書き込む。7 func Greet(w io.Writer, name string) error {8− if _, err := w.Write([]byte(fmt.Sprintf("hello, %s\n", name))); err != nil {◀9 return fmt.Errorf("write greeting: %w", err)10 }11 12 return nil13 }
8行目preferFprint: fmt.Fprintf(w, "hello, %s\n", name) should be preferred to the w.Write([]byte(fmt.Sprintf("hello, %s\n", name)))
指摘されない
1 import (2 "fmt"3 "io"4 )5 6 // Greet は挨拶を書き込む。7 func Greet(w io.Writer, name string) error {8+ if _, err := fmt.Fprintf(w, "hello, %s\n", name); err != nil {9 return fmt.Errorf("write greeting: %w", err)10 }11 12 return nil13 }
gocritic — style と diagnostic タグのチェックを有効にし、同じ意味の書き方を短く明確なほうへ揃え、バグの可能性が高い書き方を検出する。 設定: enabled-tags: [style, diagnostic] / enabled-checks: [appendCombine, equalFold, preferFprint] / disabled-checks: [unnamedResult, sloppyReassign]
指摘される
1 // AdultAge は成人とみなす年齢。2 const AdultAge = 183 4 // IsAdult は成人かを返す。5 func IsAdult(age int) bool {6− if age >= AdultAge {◀7− return true8− }9−空行10− return false11 }
6行目S1008: should use 'return age >= AdultAge' instead of 'if age >= AdultAge { return true }; return false'
指摘されない
1 // AdultAge は成人とみなす年齢。2 const AdultAge = 183 4 // IsAdult は成人かを返す。5 func IsAdult(age int) bool {6+ return age >= AdultAge7 }
staticcheck(S 系) — staticcheck の S 系チェック(v1 の gosimple。v2 で staticcheck に統合された)。同じ意味をもっと短く書ける箇所を検出する。
指摘される
1−import "fmt"2−空行3 // TableName はテーブル名を返す。4 func TableName() string {5− return fmt.Sprintf("users")◀6 }
5行目string-format: fmt.Sprintf can be replaced with just using the string
staticcheck も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは perfsprint のメッセージです。
指摘されない
1 // TableName はテーブル名を返す。2 func TableName() string {3+ return "users"4 }
staticcheck(S 系) — staticcheck の S 系チェック(v1 の gosimple。v2 で staticcheck に統合された)。同じ意味をもっと短く書ける箇所を検出する。
指摘される
1 // Squares は 0〜n-1 の 2 乗を返す。2 func Squares(n int) []int {3 out := make([]int, 0, n)4− for i := 0; i < n; i++ {◀5 out = append(out, i*i)6 }7 8 return out9 }
4行目for loop can be changed to use an integer range (Go 1.22+)
指摘されない
1 // Squares は 0〜n-1 の 2 乗を返す。2 func Squares(n int) []int {3 out := make([]int, 0, n)4+ for i := range n {5 out = append(out, i*i)6 }7 8 return out9 }
intrange — Go 1.22 以降の「整数の range」で書ける for ループを検出する。
指摘される
1 import (2 "context"3 "errors"4 "fmt"5 "net/http"6 )7 8 var errUnavailable = errors.New("api unavailable")9 10 // Ping は外部 API に到達できるかを確かめる。11 func Ping(ctx context.Context, client *http.Client, url string) error {12− req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)◀13 if err != nil {14 return fmt.Errorf("new request: %w", err)15 }16 17 resp, err := client.Do(req)18 if err != nil {19 return fmt.Errorf("send request: %w", err)20 }21 defer resp.Body.Close()22 23− if resp.StatusCode != 200 {24 return errUnavailable25 }26 27 return nil28 }
12行目"GET" can be replaced by http.MethodGet
mnd も同じ箇所を指摘します
指摘されない
1 import (2 "context"3 "errors"4 "fmt"5 "net/http"6 )7 8 var errUnavailable = errors.New("api unavailable")9 10 // Ping は外部 API に到達できるかを確かめる。11 func Ping(ctx context.Context, client *http.Client, url string) error {12+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)13 if err != nil {14 return fmt.Errorf("new request: %w", err)15 }16 17 resp, err := client.Do(req)18 if err != nil {19 return fmt.Errorf("send request: %w", err)20 }21 defer resp.Body.Close()22 23+ if resp.StatusCode != http.StatusOK {24 return errUnavailable25 }26 27 return nil28 }
usestdlibvars — "GET" や 200 のような値を、標準ライブラリの定数(http.MethodGet / http.StatusOK)に揃える。 設定: time-month / time-layout / crypto-hash / default-rpc-path / sql-isolation-level / tls-signature-scheme / constant-kind: true / time-date-month: true
指摘される
1 import "time"2 3 // Stamp は時刻を文字列にする。4 func Stamp(t time.Time) string {5− return t.Format("2006-01-02T15:04:05Z07:00")◀6 }
5行目"2006-01-02T15:04:05Z07:00" can be replaced by time.RFC3339
指摘されない
1 import "time"2 3 // Stamp は時刻を文字列にする。4 func Stamp(t time.Time) string {5+ return t.Format(time.RFC3339)6 }
usestdlibvars — "GET" や 200 のような値を、標準ライブラリの定数(http.MethodGet / http.StatusOK)に揃える。 設定: time-month / time-layout / crypto-hash / default-rpc-path / sql-isolation-level / tls-signature-scheme / constant-kind: true / time-date-month: true
指摘される
1 import "time"2 3 // FiscalYearStart は 2026 年度の開始日を返す。4 func FiscalYearStart() time.Time {5− return time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)◀6 }
5行目"4" can be replaced by time.April
指摘されない
1 import "time"2 3 // FiscalYearStart は 2026 年度の開始日を返す。4 func FiscalYearStart() time.Time {5+ return time.Date(2026, time.April, 1, 0, 0, 0, 0, time.UTC)6 }
usestdlibvars — "GET" や 200 のような値を、標準ライブラリの定数(http.MethodGet / http.StatusOK)に揃える。 設定: time-month / time-layout / crypto-hash / default-rpc-path / sql-isolation-level / tls-signature-scheme / constant-kind: true / time-date-month: true
perfsprint · 書き方 · make fmt で自動修正
数値から文字列への変換は strconv を使う
fmt.Sprintf("%d", n) は strconv.Itoa(n) と書ける。意図が明確で速い。
指摘される
1−import "fmt"2 3 // PageParam はページ番号のクエリ値を返す。4 func PageParam(page int) string {5− return fmt.Sprintf("%d", page)◀6 }
5行目integer-format: fmt.Sprintf can be replaced with faster strconv.Itoa
指摘されない
1+import "strconv"2 3 // PageParam はページ番号のクエリ値を返す。4 func PageParam(page int) string {5+ return strconv.Itoa(page)6 }
perfsprint — fmt.Sprintf でなくても書ける変換を、strconv などの専用関数に揃える。 設定: err-error: true
指摘される
1−import "fmt"2−空行3 // Describe はエラーの説明を返す。4 func Describe(err error) string {5− return fmt.Sprint(err)◀6 }
5行目error-format: fmt.Sprint can be replaced with err.Error()
指摘されない
1 // Describe はエラーの説明を返す。2 func Describe(err error) string {3+ return err.Error()4 }
perfsprint — fmt.Sprintf でなくても書ける変換を、strconv などの専用関数に揃える。 設定: err-error: true
指摘される
1 import "strings"2 3 // Upper は大文字にする。4 func Upper(s string) string {5− return strings.ToUpper(string(s))◀6 }
5行目unnecessary conversion
指摘されない
1 import "strings"2 3 // Upper は大文字にする。4 func Upper(s string) string {5+ return strings.ToUpper(s)6 }
unconvert — すでにその型である値への不要な型変換を検出する。
指摘される
1 // Total は合計を返す。2 func Total(nums []int) int {3− return 合計(nums)4 }5 6−func 合計(nums []int) int {◀7 total := 08 for _, n := range nums {9 total += n10 }11 12 return total13 }
6行目identifier "合計" contain non-ASCII character: U+5408 '合'
指摘されない
1 // Total は合計を返す。2 func Total(nums []int) int {3+ return sum(nums)4 }5 6+func sum(nums []int) int {7 total := 08 for _, n := range nums {9 total += n10 }11 12 return total13 }
asciicheck — 識別子に ASCII 以外の文字(日本語など)を使わせない。名前は英語に揃える。
指摘される
1 import "net/http"2 3 // SetJSON は JSON 用のヘッダーを付ける。4 func SetJSON(h http.Header) {5− h.Set("content-type", "application/json")◀6 }
5行目use "Content-Type" instead of "content-type"
指摘されない
1 import "net/http"2 3 // SetJSON は JSON 用のヘッダーを付ける。4 func SetJSON(h http.Header) {5+ h.Set("Content-Type", "application/json")6 }
canonicalheader — HTTP ヘッダー名を正規形(Content-Type)で書かせる。
指摘される
1 import (2 "errors"3 "strings"4 )5 6 // ErrInvalidAddr はアドレスの形式が不正なことを表す。7 var ErrInvalidAddr = errors.New("invalid address")8 9 // Validate はアドレスの形式を確かめる。10 func Validate(s string) error {11− _, _, _, err := split(s)◀12 13 return err14 }15 16−func split(s string) (string, string, string, error) {17 scheme, rest, ok := strings.Cut(s, "://")18 if !ok {19− return "", "", "", ErrInvalidAddr20 }21 22 host, port, ok := strings.Cut(rest, ":")23 if !ok {24− return "", "", "", ErrInvalidAddr25 }26 27− return scheme, host, port, nil28 }
11行目declaration has 3 blank identifiers
revive も同じ箇所を指摘します
指摘されない
1 import (2 "errors"3 "strings"4 )5 6 // ErrInvalidAddr はアドレスの形式が不正なことを表す。7 var ErrInvalidAddr = errors.New("invalid address")8 9+// Addr は分解したアドレス。10+type Addr struct {11+ Scheme string12+ Host string13+ Port string14+}15+空行16 // Validate はアドレスの形式を確かめる。17 func Validate(s string) error {18+ _, err := parse(s)19 20 return err21 }22 23+func parse(s string) (Addr, error) {24 scheme, rest, ok := strings.Cut(s, "://")25 if !ok {26+ return Addr{}, ErrInvalidAddr27 }28 29 host, port, ok := strings.Cut(rest, ":")30 if !ok {31+ return Addr{}, ErrInvalidAddr32 }33 34+ return Addr{Scheme: scheme, Host: host, Port: port}, nil35 }
dogsled — `_, _, _, err :=` のように、捨てる戻り値が多すぎる呼び出しを検出する。
指摘される
1 import "unicode/utf8"2 3 // Length は文字数を返す。4 func Length(s string) int {5− return utf8.RuneCount([]byte(s))◀6 }
5行目avoid allocations with utf8.RuneCountInString
指摘されない
1 import "unicode/utf8"2 3 // Length は文字数を返す。4 func Length(s string) int {5+ return utf8.RuneCountInString(s)6 }
mirror — []byte と string の変換を挟まずに済む関数(bytes / strings の対になる関数)を勧める。
指摘される
1 // Larger は大きいほうを返す。2 func Larger(a, b int) int {3− m := a4− if b > a {◀5− m = b6− }7−空行8− return m9 }
4行目minmax: if statement can be modernized using max
指摘されない
1 // Larger は大きいほうを返す。2 func Larger(a, b int) int {3+ return max(a, b)4 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 // HasRole は roles に role が含まれるかを返す。2 func HasRole(roles []string, role string) bool {3− for _, r := range roles {◀4− if r == role {5− return true6− }7− }8−空行9− return false10 }
3行目slicescontains: Loop can be simplified using slices.Contains
指摘されない
1+import "slices"2+空行3 // HasRole は roles に role が含まれるかを返す。4 func HasRole(roles []string, role string) bool {5+ return slices.Contains(roles, role)6 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 import "strings"2 3 // BearerToken は Authorization ヘッダーからトークンを取り出す。4 func BearerToken(header string) string {5− if strings.HasPrefix(header, "Bearer ") {◀6− return strings.TrimPrefix(header, "Bearer ")7 }8 9 return ""10 }
5行目stringscutprefix: HasPrefix + TrimPrefix can be simplified to CutPrefix
指摘されない
1 import "strings"2 3 // BearerToken は Authorization ヘッダーからトークンを取り出す。4 func BearerToken(header string) string {5+ if token, ok := strings.CutPrefix(header, "Bearer "); ok {6+ return token7 }8 9 return ""10 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 import "sync"2 3 // RunAll は fns を並行に実行し、すべて終わるまで待つ。4 func RunAll(fns []func()) {5 var wg sync.WaitGroup6 7 for _, fn := range fns {8− wg.Add(1)9−空行10− go func() {◀11− defer wg.Done()12−空行13− fn()14− }()15 }16 17 wg.Wait()18 }
10行目waitgroupgo: Goroutine creation can be simplified using WaitGroup.Go
指摘されない
1 import "sync"2 3 // RunAll は fns を並行に実行し、すべて終わるまで待つ。4 func RunAll(fns []func()) {5 var wg sync.WaitGroup6 7 for _, fn := range fns {8+ wg.Go(fn)9 }10 11 wg.Wait()12 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 // CloneHeaders はヘッダーを複製する。2 func CloneHeaders(src map[string]string) map[string]string {3 dst := map[string]string{}4− for k, v := range src {5− dst[k] = v◀6− }7 8 return dst9 }
5行目mapsloop: Replace m[k]=v loop with maps.Copy
指摘されない
1+import "maps"2+空行3 // CloneHeaders はヘッダーを複製する。4 func CloneHeaders(src map[string]string) map[string]string {5 dst := map[string]string{}6+ maps.Copy(dst, src)7 8 return dst9 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 import "strings"2 3 // CountTags はカンマ区切りの空でないタグを数える。4 func CountTags(s string) int {5 n := 06 7− for _, tag := range strings.Split(s, ",") {◀8 if tag != "" {9 n++10 }11 }12 13 return n14 }
7行目stringsseq: Ranging over SplitSeq is more efficient
指摘されない
1 import "strings"2 3 // CountTags はカンマ区切りの空でないタグを数える。4 func CountTags(s string) int {5 n := 06 7+ for tag := range strings.SplitSeq(s, ",") {8 if tag != "" {9 n++10 }11 }12 13 return n14 }
modernize — 新しい Go の言語機能・標準ライブラリで書ける古い書き方を検出する(min / max、slices、maps、strings.CutPrefix、WaitGroup.Go など)。Go チーム公式の解析。
指摘される
1 // Role は権限。2 type Role int3 4 // 権限の一覧。5 const (◀6 RoleGuest Role = iota7 RoleMember8 RoleAdmin9− MaxNameLength = 3210 )
5行目iota mixing. keep iotas in separate blocks to consts with r-val
指摘されない
1 // Role は権限。2 type Role int3 4 // 権限の一覧。5 const (6 RoleGuest Role = iota7 RoleMember8 RoleAdmin9 )10+空行11+// MaxNameLength は名前の最大文字数。12+const MaxNameLength = 32
iotamixing — iota を使う const ブロックに、iota と関係のない定数を混ぜない。
指摘される
1 import "errors"2 3 // ErrNotFound はユーザーが存在しないことを表す。4−var ErrNotFound = errors.New("ユーザーが見つかりません")◀
4行目string literal contains rune in Han script
指摘されない
1 import "errors"2 3 // ErrNotFound はユーザーが存在しないことを表す。4+var ErrNotFound = errors.New("user not found")
gosmopolitan — 本番コードの文字列リテラル(エラー・ログのメッセージ)に日本語などを書かせない。メッセージは英語に揃える。テストのケース名は対象外。
指摘される
1 import "strings"2 3 // Normalize は名前を正規化する。4 func Normalize(name string) string {5 result := strings.TrimSpace(name)◀6− result = strings.ToLower(name)7 8 return result9 }
5行目ineffectual assignment to result
指摘されない
1 import "strings"2 3 // Normalize は名前を正規化する。4 func Normalize(name string) string {5 result := strings.TrimSpace(name)6+ result = strings.ToLower(result)7 8 return result9 }
ineffassign — 代入したのに一度も読まれないまま上書きされる値を検出する。
指摘される
1 import "strings"2 3 func normalize(s string) string {◀4 return strings.TrimSpace(s)5 }
3行目func normalize is unused
指摘されない
1 import "strings"2+空行3+// NormalizeName は名前の前後の空白を取り除く。4+func NormalizeName(s string) string {5+ return normalize(s)6+}7 8 func normalize(s string) string {9 return strings.TrimSpace(s)10 }
unused — どこからも使われていない非公開の関数・型・定数・変数・フィールドを検出する。 設定: field-writes-are-uses: false
指摘される
1 type stats struct {2 count int3− last int◀4 }5 6 // Count は件数を返す。7 func Count(xs []int) int {8 s := stats{}9− for _, x := range xs {10 s.count++11− s.last = x◀12 }13 14 return s.count15 }
11行目unusedwrite: unused write to field last
3行目field last is unused
unused も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは govet のメッセージです。
指摘されない
1 type stats struct {2 count int3 }4 5 // Count は件数を返す。6 func Count(xs []int) int {7 s := stats{}8+ for range xs {9 s.count++10 }11 12 return s.count13 }
unused — どこからも使われていない非公開の関数・型・定数・変数・フィールドを検出する。 設定: field-writes-are-uses: false
指摘される
1 import "sync"2 3 // Run は関数を並行に実行する。4 func Run(fns []func()) {5 var wg sync.WaitGroup6 for _, fn := range fns {7− fn := fn◀8−空行9 wg.Go(fn)10 }11 12 wg.Wait()13 }
7行目The copy of the 'for' variable "fn" can be deleted (Go 1.22+)
wsl_v5 も同じ箇所を指摘します
指摘されない
1 import "sync"2 3 // Run は関数を並行に実行する。4 func Run(fns []func()) {5 var wg sync.WaitGroup6 for _, fn := range fns {7 wg.Go(fn)8 }9 10 wg.Wait()11 }
copyloopvar — Go 1.22 以降は不要になった `v := v` のループ変数のコピーを検出する。 設定: check-alias: true
指摘される
1 // Pointers は各要素へのポインタを返す。2 func Pointers(values []int) []*int {3 out := make([]*int, 0, len(values))4 for _, v := range values {5− item := v◀6− out = append(out, &item)7 }8 9 return out10 }
5行目The copy of the 'for' variable "v" can be deleted (Go 1.22+)
指摘されない
1 // Pointers は各要素へのポインタを返す。2 func Pointers(values []int) []*int {3 out := make([]*int, 0, len(values))4 for _, v := range values {5+ out = append(out, &v)6 }7 8 return out9 }
copyloopvar — Go 1.22 以降は不要になった `v := v` のループ変数のコピーを検出する。 設定: check-alias: true
指摘される
1−import "fmt"2 3 // LogCreated はユーザー作成を記録する。4 func LogCreated(id string) {5− fmt.Println("user created:", id)◀6 }
5行目use of `fmt.Println` forbidden because "ログは log/slog を使う"
指摘されない
1+import "log/slog"2 3 // LogCreated はユーザー作成を記録する。4 func LogCreated(id string) {5+ slog.Info("user created", "user_id", id)6 }
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
1−import "strings"2 3 // Normalize は前後の空白を取り除く。4 func Normalize(name string) string {5− println("name =", name)◀6 7 return strings.TrimSpace(name)8 }
5行目use of `println` forbidden because "ログは log/slog を使う"
指摘されない
1+import (2+ "log/slog"3+ "strings"4+)5 6 // Normalize は前後の空白を取り除く。7 func Normalize(name string) string {8+ slog.Debug("normalize", "name", name)9 10 return strings.TrimSpace(name)11 }
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
このプロジェクトでの使われ方
- 1
TxManager と UserRepository は、同じ *sql.DB を受け取るだけ。2 つの間でトランザクションを受け渡す口はない。
cmd/api/main.go:55-56
55 txManager := repository.NewTxManager(db)56 userRepo := repository.NewUserRepository(db)
- 2
usecase は「重複確認 → 作成」を TxManager.Do で囲み、受け取った ctx をそのまま repository に渡す。usecase は database/sql を import できない(depguard)ので、*sql.Tx を直接扱えない。
internal/usecase/user.go:54-69
54 txErr := uc.tx.Do(ctx, func(ctx context.Context) error {55 exists, err := uc.repo.ExistsByEmail(ctx, email)56 if err != nil {57 return fmt.Errorf("exists by email: %w", err)58 }59 60 if exists {61 return user.ErrEmailAlreadyExists62 }63 64 if err := uc.repo.Create(ctx, u); err != nil {65 return fmt.Errorf("create user: %w", err)66 }67 68 return nil69 })
- 3
Do はトランザクションを始め、ctx に入れてから処理を呼ぶ。トランザクションの受け渡しは、この ctx だけで行われる。
internal/adapter/repository/tx.go:54
54 if err = fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
- 4
conn は ctx にトランザクションがあればそれを、なければ r.db を返す。
internal/adapter/repository/db.go:19-25
19 // conn は ctx にトランザクションがあればそれを、なければ db を返す。20 func conn(ctx context.Context, db *sql.DB) querier { //nolint:ireturn // *sql.DB と *sql.Tx を同じ型で扱うため21 if tx, ok := ctx.Value(txKey{}).(*sql.Tx); ok {22 return tx23 }24 25 return db
- 5
repository は conn 経由で SQL を実行する。Do の中で呼ばれたときは、自動でトランザクションに参加する。
internal/adapter/repository/user.go:43
43 _, err := conn(ctx, r.db).ExecContext(ctx, q, u.ID().String(), u.Name(), u.Email().String(), u.CreatedAt())
r.db を直接使うとr.db を直接使うと、Do が ctx に入れたトランザクションは誰にも取り出されず、Create は別の接続でその場で確定する。今の UserUsecase.Create は書き込みが Create の 1 回だけなので実害は小さい。ただ、書き込みを 2 回する機能を足して 2 回目が失敗すると、1 回目だけが DB に残る。コンパイルは通り、usecase のテストは fake を使うので気付けない。
指摘される
internal/adapter/repository/user.go
1 package repository2 3 import (4 "context"5 "database/sql"6 "fmt"7 8 "example.com/go-clean/internal/domain/user"9 )10 11 // UserRepository は usecase.UserRepository の PostgreSQL 実装。12 type UserRepository struct {13 db *sql.DB14 }15 16 // Create はユーザーを保存する。メールアドレスが重複していれば user.ErrEmailAlreadyExists を返す。17 func (r *UserRepository) Create(ctx context.Context, u *user.User) error {18 const q = `19 INSERT INTO users (20 id,21 name,22 email,23 created_at24 )25 VALUES (26 $1,27 $2,28 $3,29 $430 )31 `32 33− _, err := r.db.ExecContext(ctx, q, u.ID().String(), u.Name(), u.Email().String(), u.CreatedAt())◀34 if isUniqueViolation(err) {35 return user.ErrEmailAlreadyExists36 }37 38 if err != nil {39 return fmt.Errorf("insert user: %w", err)40 }41 42 return nil43 }
33行目use of `r.db.ExecContext` forbidden because "repository は conn(ctx, r.db) 経由で DB にアクセスする(トランザクションに自動で参加するため)"
指摘されない
internal/adapter/repository/user.go
1 package repository2 3 import (4 "context"5 "database/sql"6 "fmt"7 8 "example.com/go-clean/internal/domain/user"9 )10 11 // UserRepository は usecase.UserRepository の PostgreSQL 実装。12 type UserRepository struct {13 db *sql.DB14 }15 16 // Create はユーザーを保存する。メールアドレスが重複していれば user.ErrEmailAlreadyExists を返す。17 func (r *UserRepository) Create(ctx context.Context, u *user.User) error {18 const q = `19 INSERT INTO users (20 id,21 name,22 email,23 created_at24 )25 VALUES (26 $1,27 $2,28 $3,29 $430 )31 `32 33+ _, err := conn(ctx, r.db).ExecContext(ctx, q, u.ID().String(), u.Name(), u.Email().String(), u.CreatedAt())34 if isUniqueViolation(err) {35 return user.ErrEmailAlreadyExists36 }37 38 if err != nil {39 return fmt.Errorf("insert user: %w", err)40 }41 42 return nil43 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 analyze-types: true # 型で判定する(r.db が *sql.DB かどうか)5 forbid:6 # (ほかの 3 つのパターンは省略)7 - pattern: ^sql\.DB\.(Exec|Query|QueryRow)Context$8 msg: repository は conn(ctx, r.db) 経由で DB にアクセスする(トランザクションに自動で参加するため)9 exclusions:10 rules:11 - path-except: internal/adapter/repository/ # conn 経由のルールは repository だけに適用する12 linters:13 - forbidigo14 text: conn\(ctx, r\.db\)
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/usecase/order.go
1 package usecase2 3 import "context"4 5 // OrderUsecase は注文に関するユースケース。6 type OrderUsecase struct {7− users *UserUsecase8 orders OrderRepository9 }10 11 // Create は注文者を確かめてから注文を作成する。12 func (uc *OrderUsecase) Create(ctx context.Context, userID, item string) error {13− u, err := uc.users.Get(ctx, userID)◀14 if err != nil {15 return err16 }17 18 return uc.orders.Create(ctx, u.ID, item)19 }
13行目use of `uc.users.Get` forbidden because "usecase から他の usecase を呼ばない。必要なデータは port から取り、共通の処理は domain へ寄せる"
指摘されない
internal/usecase/order.go
1 package usecase2 3 import "context"4 5 // OrderUsecase は注文に関するユースケース。6 type OrderUsecase struct {7+ users UserRepository8 orders OrderRepository9 }10 11 // Create は注文者を確かめてから注文を作成する。12 func (uc *OrderUsecase) Create(ctx context.Context, userID, item string) error {13+ u, err := uc.users.FindByID(ctx, userID)14 if err != nil {15 return err16 }17 18 return uc.orders.Create(ctx, u.ID, item)19 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^usecase\.New\w+$6 msg: usecase の生成(DI)は cmd/api/main.go でだけ行う7 - pattern: ^user\.User$ # 集約を足したら、そのエンティティのパターンと exclusions の 1 行を足す8 msg: 他の集約は ID だけで参照する(user.User)9 - pattern: ^usecase\.\w+Usecase\.[A-Z]\w*$ # XxxUsecase のメソッド呼び出し(フィールドは小文字なので対象外)10 msg: usecase から他の usecase を呼ばない。必要なデータは port から取り、共通の処理は domain へ寄せる11 exclusions:12 rules:13 - path-except: internal/usecase/ # usecase を呼ばないルールは usecase の中だけに適用する14 linters:15 - forbidigo16 text: usecase から他の usecase を呼ばない
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/handler/health.go
1 package handler2 3 import (4 "net/http"5 6 "github.com/gin-gonic/gin"7 )8 9 // Health は GET /healthz を処理する。10 func Health(c *gin.Context) {11− c.JSON(http.StatusOK, gin.H{"status": "ok"})◀12 }
11行目use of `gin.H` forbidden because "レスポンスは dto.go の構造体で返す"
指摘されない
internal/adapter/handler/health.go
1 package handler2 3 import (4 "net/http"5 6 "github.com/gin-gonic/gin"7 )8 9 // Health は GET /healthz を処理する。10 func Health(c *gin.Context) {11+ c.JSON(http.StatusOK, healthResponse{Status: "ok"})12 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^gin\.H$6 msg: レスポンスは dto.go の構造体で返す
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/handler/user.go
1 package handler2 3 import (4− "fmt"5−空行6 "github.com/gin-gonic/gin"7 )8 9 // readCreateUser はリクエストの JSON を読む。10 func readCreateUser(c *gin.Context) (createUserRequest, error) {11 var req createUserRequest12− if err := c.ShouldBindJSON(&req); err != nil {◀13− return createUserRequest{}, fmt.Errorf("%w: %w", errInvalidJSON, err)14 }15 16 return req, nil17 }18 19 var _ = readCreateUser
12行目use of `c.ShouldBindJSON` forbidden because "リクエストの JSON は decodeJSON で読む(未知のフィールドの拒否とサイズの上限のため)"
指摘されない
internal/adapter/handler/user.go
1 package handler2 3 import (4 "github.com/gin-gonic/gin"5 )6 7 // readCreateUser はリクエストの JSON を読む。8 func readCreateUser(c *gin.Context) (createUserRequest, error) {9 var req createUserRequest10+ if err := decodeJSON(c, &req); err != nil {11+ return createUserRequest{}, err12 }13 14 return req, nil15 }16 17 var _ = readCreateUser
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^gin\.Context\.(Bind|ShouldBind|MustBind)\w*$6 msg: リクエストの JSON は decodeJSON で読む(未知のフィールドの拒否とサイズの上限のため)
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/handler/router.go
1 package handler2 3 import (4 "net/http"5 6 "github.com/gin-gonic/gin"7 )8 9 // NewRouter はルーティングを組み立てた http.Handler を返す。10 func NewRouter() http.Handler {11− r := gin.Default()◀12 r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusOK) })13 14 return r15 }
11行目use of `gin.Default` forbidden because "gin.New を使う(ログとパニック回復は自前のミドルウェアで行う)"
指摘されない
internal/adapter/handler/router.go
1 package handler2 3 import (4 "net/http"5 6 "github.com/gin-gonic/gin"7 )8 9 // NewRouter はルーティングを組み立てた http.Handler を返す。10 func NewRouter() http.Handler {11+ r := gin.New()12+ r.Use(recoverPanic, logRequest)13 r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusOK) })14 15 return r16 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^gin\.Default$6 msg: gin.New を使う(ログとパニック回復は自前のミドルウェアで行う)
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/domain/order/order.go
1 // Package order は注文集約。2 package order3 4 import "time"5 6 // Order は注文エンティティ。7 type Order struct {8 item string9 createdAt time.Time10 }11 12 // New は注文を生成する。13−func New(item string) *Order {14− return &Order{item: item, createdAt: time.Now()}◀15 }16 17 // Item は品目を返す。18 func (o *Order) Item() string { return o.item }19 20 // CreatedAt は作成日時を返す。21 func (o *Order) CreatedAt() time.Time { return o.createdAt }
14行目use of `time.Now` forbidden because "現在時刻は usecase の now フィールドから受け取る"
指摘されない
internal/domain/order/order.go
1 // Package order は注文集約。2 package order3 4 import "time"5 6 // Order は注文エンティティ。7 type Order struct {8 item string9 createdAt time.Time10 }11 12 // New は注文を生成する。13+func New(item string, now time.Time) *Order {14+ return &Order{item: item, createdAt: now}15 }16 17 // Item は品目を返す。18 func (o *Order) Item() string { return o.item }19 20 // CreatedAt は作成日時を返す。21 func (o *Order) CreatedAt() time.Time { return o.createdAt }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^time\.Now$6 msg: 現在時刻は usecase の now フィールドから受け取る7 exclusions:8 rules:9 - path-except: internal/(domain|usecase|adapter/repository)/10 linters: [forbidigo]11 text: 現在時刻は usecase の now12 - path: internal/usecase/13 linters: [forbidigo]14 text: 現在時刻は usecase の now15 source: 'now:\s+time\.Now' # コンストラクタで now の既定値を入れる行だけは許す
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/usecase/report.go
1 package usecase2 3 import (4 "context"5 "fmt"6 )7 8 // ReportUsecase はレポートに関するユースケース。9 type ReportUsecase struct {10 store ReportStore11 }12 13 // Create はレポートを保存する。14−func (uc *ReportUsecase) Create(body string) error {15− if err := uc.store.Save(context.Background(), body); err != nil {◀16 return fmt.Errorf("save report: %w", err)17 }18 19 return nil20 }
15行目use of `context.Background` forbidden because "呼び出し元から受け取った ctx を使う"
指摘されない
internal/usecase/report.go
1 package usecase2 3 import (4 "context"5 "fmt"6 )7 8 // ReportUsecase はレポートに関するユースケース。9 type ReportUsecase struct {10 store ReportStore11 }12 13 // Create はレポートを保存する。14+func (uc *ReportUsecase) Create(ctx context.Context, body string) error {15+ if err := uc.store.Save(ctx, body); err != nil {16 return fmt.Errorf("save report: %w", err)17 }18 19 return nil20 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^context\.(Background|TODO)$6 msg: 呼び出し元から受け取った ctx を使う7 exclusions:8 rules:9 - path: cmd/10 linters: [forbidigo]11 text: 呼び出し元から受け取った ctx
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/mail/mail.go
1 // Package mail はメール送信 API の adapter。2 package mail3 4 import (5 "net/http"6− "os"7 )8 9 // Mailer はメール送信 API のクライアント。10 type Mailer struct {11 client *http.Client12 endpoint string13 }14 15 // NewMailer は Mailer を生成する。16−func NewMailer(client *http.Client) *Mailer {17− return &Mailer{client: client, endpoint: os.Getenv("MAIL_ENDPOINT")}◀18 }
17行目use of `os.Getenv` forbidden because "環境変数は infra/config でだけ読む"
指摘されない
internal/adapter/mail/mail.go
1 // Package mail はメール送信 API の adapter。2 package mail3 4 import (5 "net/http"6 )7 8 // Mailer はメール送信 API のクライアント。9 type Mailer struct {10 client *http.Client11 endpoint string12 }13 14 // NewMailer は Mailer を生成する。15+func NewMailer(client *http.Client, endpoint string) *Mailer {16+ return &Mailer{client: client, endpoint: endpoint}17 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^os\.(Getenv|LookupEnv|Environ)$6 msg: 環境変数は infra/config でだけ読む7 exclusions:8 rules:9 - path: internal/infra/config/10 linters: [forbidigo]11 text: 環境変数は infra/config
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/repository/user.go
1 package repository2 3 import (4 "database/sql"5− "fmt"6 )7 8 // UserRepository は usecase.UserRepository の PostgreSQL 実装。9 type UserRepository struct {10 db *sql.DB11 }12 13 // NewUserRepository は UserRepository を生成する。14−func NewUserRepository(dsn string) (*UserRepository, error) {15− db, err := sql.Open("pgx", dsn)◀16− if err != nil {17− return nil, fmt.Errorf("open db: %w", err)18− }19−空行20− return &UserRepository{db: db}, nil21 }
15行目use of `sql.Open` forbidden because "DB 接続は infra/database でだけ作る"
指摘されない
internal/adapter/repository/user.go
1 package repository2 3 import (4 "database/sql"5 )6 7 // UserRepository は usecase.UserRepository の PostgreSQL 実装。8 type UserRepository struct {9 db *sql.DB10 }11 12 // NewUserRepository は UserRepository を生成する。13+func NewUserRepository(db *sql.DB) *UserRepository {14+ return &UserRepository{db: db}15 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^sql\.Open$6 msg: DB 接続は infra/database でだけ作る7 exclusions:8 rules:9 - path: internal/infra/database/10 linters: [forbidigo]11 text: DB 接続は infra/database
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/mail/mail.go
1 // Package mail はメール送信 API の adapter。2 package mail3 4 import (5 "net/http"6 )7 8 // Mailer はメール送信 API のクライアント。9 type Mailer struct {10 client *http.Client11 endpoint string12 }13 14 // NewMailer は Mailer を生成する。15−func NewMailer(endpoint string) *Mailer {16− return &Mailer{client: http.DefaultClient, endpoint: endpoint}◀17 }
16行目use of `http.DefaultClient` forbidden because "http.Client は cmd で作ってコンストラクタで受け取る"
指摘されない
internal/adapter/mail/mail.go
1 // Package mail はメール送信 API の adapter。2 package mail3 4 import (5 "net/http"6 )7 8 // Mailer はメール送信 API のクライアント。9 type Mailer struct {10 client *http.Client11 endpoint string12 }13 14 // NewMailer は Mailer を生成する。15+func NewMailer(client *http.Client, endpoint string) *Mailer {16+ return &Mailer{client: client, endpoint: endpoint}17 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^http\.DefaultClient$6 msg: http.Client は cmd で作ってコンストラクタで受け取る7 exclusions:8 rules:9 - path: cmd/10 linters: [forbidigo]11 text: http\.Client は cmd
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/adapter/handler/user.go
1 package handler2 3−import "example.com/go-clean/internal/usecase"4 5 // UserHandler はユーザー API のハンドラ。6 type UserHandler struct {7− users *usecase.UserUsecase8 }9 10 // NewUserHandler は UserHandler を生成する。11−func NewUserHandler(repo usecase.UserRepository, tx usecase.TxManager) *UserHandler {12− return &UserHandler{users: usecase.NewUserUsecase(repo, tx)}◀13 }
12行目use of `usecase.NewUserUsecase` forbidden because "usecase の生成(DI)は cmd/api/main.go でだけ行う"
指摘されない
internal/adapter/handler/user.go
1 package handler2 3+import (4+ "context"5+空行6+ "example.com/go-clean/internal/usecase"7+)8+空行9+type userUsecase interface {10+ Get(ctx context.Context, in usecase.GetUserInput) (*usecase.UserOutput, error)11+}12 13 // UserHandler はユーザー API のハンドラ。14 type UserHandler struct {15+ users userUsecase16 }17 18 // NewUserHandler は UserHandler を生成する。19+func NewUserHandler(users userUsecase) *UserHandler {20+ return &UserHandler{users: users}21 }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^usecase\.New\w+$6 msg: usecase の生成(DI)は cmd/api/main.go でだけ行う7 exclusions:8 rules:9 - path: cmd/10 linters: [forbidigo]11 text: usecase の生成
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
internal/domain/order/order.go
1 // Package order は注文集約。2 package order3 4 import "example.com/go-clean/internal/domain/user"5 6 // Order は注文エンティティ。7 type Order struct {8− item string9− owner *user.User◀10 }11 12 // New は注文を生成する。13−func New(item string, owner *user.User) *Order {◀14− return &Order{item: item, owner: owner}15 }16 17 // Item は品目を返す。18 func (o *Order) Item() string { return o.item }19 20−// Owner は注文者を返す。21−func (o *Order) Owner() *user.User { return o.owner }◀
9行目use of `user.User` forbidden because "他の集約は ID だけで参照する(user.User)"
13行目use of `user.User` forbidden because "他の集約は ID だけで参照する(user.User)"
21行目use of `user.User` forbidden because "他の集約は ID だけで参照する(user.User)"
指摘されない
internal/domain/order/order.go
1 // Package order は注文集約。2 package order3 4 import "example.com/go-clean/internal/domain/user"5 6 // Order は注文エンティティ。7 type Order struct {8+ item string9+ userID user.ID10 }11 12 // New は注文を生成する。13+func New(item string, userID user.ID) *Order {14+ return &Order{item: item, userID: userID}15 }16 17 // Item は品目を返す。18 func (o *Order) Item() string { return o.item }19 20+// UserID は注文者のユーザー ID を返す。21+func (o *Order) UserID() user.ID { return o.userID }
.golangci.yml の設定
1 linters:2 settings:3 forbidigo:4 forbid:5 - pattern: ^user\.User$ # 集約を足したら、そのエンティティのパターンと exclusions の 1 行を足す6 msg: 他の集約は ID だけで参照する(user.User)7 exclusions:8 rules:9 - path-except: internal/domain/ # 他の集約の参照は domain だけで止める10 linters: [forbidigo]11 text: 他の集約は ID だけで参照する12 - path: internal/domain/user/ # 自分の集約のエンティティは使ってよい13 linters: [forbidigo]14 text: ID だけで参照する(user\.User)
forbidigo — 使ってはいけない関数を禁止する。デバッグ用の fmt.Println や log.Printf を残さず、ログは log/slog に統一する。 設定: forbid: ^fmt\.Print.*$ / ^log\.(Print|Fatal|Panic).*$ / ^print(ln)?$ / analyze-types: true / ^sql\.DB\.(Exec|Query|QueryRow)Context$(repository だけ) / ^usecase\.\w+Usecase\.[A-Z]\w*$(usecase だけ) / gin.H・ShouldBind・gin.Default・time.Now・context.Background・os.Getenv・sql.Open・http.DefaultClient・usecase.New・他の集約のエンティティ(層ごとに exclusions で絞る)
指摘される
1 import "time"2 3 // Timeout は外部 API のタイムアウト。4−// TODO: 設定ファイルから読む◀5 const Timeout = 3 * time.Second
4行目Line contains TODO/BUG/FIXME/HACK/XXX: "TODO: 設定ファイルから読む"
指摘されない
1 import "time"2 3 // Timeout は外部 API のタイムアウト。4 const Timeout = 3 * time.Second
godox — TODO / FIXME / BUG のコメントを検出する。やり残しはコードに残さず、チケットで管理する。 設定: keywords: [TODO, BUG, FIXME, HACK, XXX]
指摘される
1 // Retry は 3 回まで fn を試す。2−// HACK: 失敗の原因を調べずに回数だけ増やしている。◀3 func Retry(fn func() error) error {4 const maxAttempts = 35 6 var err error7 for range maxAttempts {8 err = fn()9 if err == nil {10 return nil11 }12 }13 14 return err15 }
2行目Line contains TODO/BUG/FIXME/HACK/XXX: "HACK: 失敗の原因を調べずに回数だけ増やしている。..."
指摘されない
1 // Retry は 3 回まで fn を試す。2 func Retry(fn func() error) error {3 const maxAttempts = 34 5 var err error6 for range maxAttempts {7 err = fn()8 if err == nil {9 return nil10 }11 }12 13 return err14 }
godox — TODO / FIXME / BUG のコメントを検出する。やり残しはコードに残さず、チケットで管理する。 設定: keywords: [TODO, BUG, FIXME, HACK, XXX]
指摘される
1 import "unicode/utf8"2 3 // ValidName は名前の長さが上限以内かを返す。4 func ValidName(name string) bool {5− return utf8.RuneCountInString(name) <= 50◀6 }
5行目Magic number: 50, in <return> detected
指摘されない
1 import "unicode/utf8"2+空行3+// MaxNameLength は名前の最大文字数。4+const MaxNameLength = 505 6 // ValidName は名前の長さが上限以内かを返す。7 func ValidName(name string) bool {8+ return utf8.RuneCountInString(name) <= MaxNameLength9 }
mnd — 意味の説明がない数値(マジックナンバー)を検出する。名前の付いた定数にする。
指摘される
1 const (2 gradeA = 803 gradeB = 604 maxScore = 1005 )6 7 // Classify は点数を評価ごとに数える。8 func Classify(scores [][]int) map[string]int {◀9 counts := map[string]int{}10 11 for _, row := range scores {12 for _, s := range row {13 if s < 0 || s > maxScore {14 continue15 }16 17− if s >= gradeA {18− if s == maxScore {19− counts["perfect"]++20− }21−空行22− counts["A"]++23− } else if s >= gradeB {24− counts["B"]++25− } else {26− if s == 0 {27− counts["zero"]++28− }29−空行30− counts["C"]++31− }32 }33 }34 35 return counts36 }
8行目cognitive complexity 19 of func `Classify` is high (> 15)
gocritic も同じ箇所を指摘します
指摘されない
1 const (2 gradeA = 803 gradeB = 604 maxScore = 1005 )6 7 // Classify は点数を評価ごとに数える。8 func Classify(scores [][]int) map[string]int {9 counts := map[string]int{}10 11 for _, row := range scores {12 for _, s := range row {13 if s < 0 || s > maxScore {14 continue15 }16 17+ counts[grade(s)]++18 }19 }20 21 return counts22 }23+空行24+func grade(s int) string {25+ switch {26+ case s >= gradeA:27+ return "A"28+ case s >= gradeB:29+ return "B"30+ default:31+ return "C"32+ }33+}
gocognit — 関数の認知的複雑度(ネストや分岐の多さ)の上限。超えたら関数を分ける。 設定: min-complexity: 15
指摘される
1 const (2 minTotal = 50003 noCouponTotal = 100004 discount = 105 )6 7 // Discount は割引率を返す。8 func Discount(member, coupon bool, total int) int {9− if member {◀10− if coupon {11− if total >= minTotal {12− return discount13− }14− } else {15− if total >= noCouponTotal {16− return discount17− }18− }19 }20 21− return 022 }
9行目`if member` has complex nested blocks (complexity: 6)
指摘されない
1 const (2 minTotal = 50003 noCouponTotal = 100004 discount = 105 )6 7 // Discount は割引率を返す。8 func Discount(member, coupon bool, total int) int {9+ if !member {10+ return 011 }12 13+ threshold := minTotal14+ if !coupon {15+ threshold = noCouponTotal16+ }17+空行18+ if total < threshold {19+ return 020+ }21+空行22+ return discount23 }
nestif — if のネストが深すぎる箇所を検出する。早めに return してネストを浅くする。 設定: min-complexity: 4
指摘される
1 import (2 "slices"3 "strings"4 )5 6−// AdminNames は管理者の名前を整形して返す。7−func AdminNames(names []string, roles map[string]string) []string {◀8 seen := map[string]bool{}9 out := make([]string, 0, len(names))10 11 for _, n := range names {12− if roles[n] != "admin" {13 continue14 }15 16 trimmed := strings.ToUpper(strings.TrimSpace(n))17 if trimmed == "" || seen[trimmed] {18 continue19 }20 21 seen[trimmed] = true22 23 out = append(out, trimmed)24 }25 26 slices.Sort(out)27 28 return out29 }30−空行31−// OwnerNames は所有者の名前を整形して返す。32−func OwnerNames(names []string, roles map[string]string) []string {◀33− seen := map[string]bool{}34− out := make([]string, 0, len(names))35−空行36− for _, n := range names {37− if roles[n] != "owner" {38− continue39− }40−空行41− trimmed := strings.ToUpper(strings.TrimSpace(n))42− if trimmed == "" || seen[trimmed] {43− continue44− }45−空行46− seen[trimmed] = true47−空行48− out = append(out, trimmed)49− }50−空行51− slices.Sort(out)52−空行53− return out54−}
7行目10-32 lines are duplicate of `internal/cases/q_dupl_bad/q_dupl_bad.go:35-57`
32行目35-57 lines are duplicate of `internal/cases/q_dupl_bad/q_dupl_bad.go:10-32`
指摘されない
1 import (2 "slices"3 "strings"4 )5 6+// NamesByRole は指定した役割の名前を整形して返す。7+func NamesByRole(names []string, roles map[string]string, role string) []string {8 seen := map[string]bool{}9 out := make([]string, 0, len(names))10 11 for _, n := range names {12+ if roles[n] != role {13 continue14 }15 16 trimmed := strings.ToUpper(strings.TrimSpace(n))17 if trimmed == "" || seen[trimmed] {18 continue19 }20 21 seen[trimmed] = true22 23 out = append(out, trimmed)24 }25 26 slices.Sort(out)27 28 return out29 }
dupl — ほぼ同じ内容のコードブロックを検出する。共通部分を関数にまとめる。 設定: threshold: 75(_test.go は対象外)
指摘される
1 // CanEdit は編集できるかを返す。2 func CanEdit(role string) bool {3− return role == "admin"◀4 }5 6 // CanDelete は削除できるかを返す。7 func CanDelete(role string) bool {8− return role == "admin"9 }10 11 // CanInvite は招待できるかを返す。12 func CanInvite(role string) bool {13− return role == "admin"14 }
3行目string `admin` has 3 occurrences, make it a constant
指摘されない
1+// RoleAdmin は管理者の役割名。2+const RoleAdmin = "admin"3+空行4 // CanEdit は編集できるかを返す。5 func CanEdit(role string) bool {6+ return role == RoleAdmin7 }8 9 // CanDelete は削除できるかを返す。10 func CanDelete(role string) bool {11+ return role == RoleAdmin12 }13 14 // CanInvite は招待できるかを返す。15 func CanInvite(role string) bool {16+ return role == RoleAdmin17 }
goconst — 同じ文字列リテラルが何度も出てくる箇所を検出する。定数にまとめる。
指摘される
1−// Close closes the the connection.◀2 func Close() {}
1行目Duplicate words (the) found
指摘されない
1+// Close closes the connection.2 func Close() {}
dupword — コメントや文字列の中で同じ単語が続く誤り(the the など)を検出する。
指摘される
1 import "strings"2 3 // Split はメールアドレスをローカル部とドメインに分ける。4−func Split(email string) (local, domain string) {◀5− local, domain, _ = strings.Cut(email, "@")6 7 return local, domain8 }
4行目named return "local" with type "string" found
指摘されない
1 import "strings"2 3 // Split はメールアドレスをローカル部とドメインに分ける。4+func Split(email string) (string, string) {5+ local, domain, _ := strings.Cut(email, "@")6 7 return local, domain8 }
nonamedreturns — 名前付きの戻り値を使わない。defer の中で err を書き換える用途(repository/tx.go)は既定で許可される。
指摘される
1 import (2 "context"3 "fmt"4 )5 6 // UserFinder はユーザーを探す port。7 type UserFinder interface {8− Find(context.Context, string) (string, error)◀9 }10 11 // Greeting は挨拶文を返す。12 func Greeting(ctx context.Context, f UserFinder, id string) (string, error) {13 name, err := f.Find(ctx, id)14 if err != nil {15 return "", fmt.Errorf("find user: %w", err)16 }17 18 return "hello, " + name, nil19 }
8行目interface method Find must have named param for type context.Context
指摘されない
1 import (2 "context"3 "fmt"4 )5 6 // UserFinder はユーザーを探す port。7 type UserFinder interface {8+ Find(ctx context.Context, id string) (string, error)9 }10 11 // Greeting は挨拶文を返す。12 func Greeting(ctx context.Context, f UserFinder, id string) (string, error) {13 name, err := f.Find(ctx, id)14 if err != nil {15 return "", fmt.Errorf("find user: %w", err)16 }17 18 return "hello, " + name, nil19 }
inamedparam — interface のメソッドの引数に名前を付け、何を渡すのかを読めるようにする。
指摘される
1 import (2 "fmt"3 "net/http"4 )5 6 // HealthStatus はヘルスチェックのステータスコードを返す。7−func HealthStatus() (int, error) {8− resp, err := http.Get("https://example.com/health")◀9 if err != nil {10− return 0, fmt.Errorf("get: %w", err)11 }12 13 defer resp.Body.Close()14 15 return resp.StatusCode, nil16 }
8行目net/http.Get must not be called. use net/http.NewRequestWithContext and (*net/http.Client).Do(*http.Request)
指摘されない
1 import (2+ "context"3 "fmt"4 "net/http"5 )6 7 // HealthStatus はヘルスチェックのステータスコードを返す。8+func HealthStatus(ctx context.Context, client *http.Client) (int, error) {9+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/health", http.NoBody)10 if err != nil {11+ return 0, fmt.Errorf("new request: %w", err)12+ }13+空行14+ resp, err := client.Do(req)15+ if err != nil {16+ return 0, fmt.Errorf("do request: %w", err)17 }18 19 defer resp.Body.Close()20 21 return resp.StatusCode, nil22 }
noctx — context を渡さない HTTP リクエストを禁止する。
指摘される
1 import (2 "context"3 "fmt"4 "net/http"5 )6 7 // HealthStatus はヘルスチェックのステータスコードを返す。8 func HealthStatus(ctx context.Context, client *http.Client) (int, error) {9 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/health", http.NoBody)10 if err != nil {11 return 0, fmt.Errorf("new request: %w", err)12 }13 14 resp, err := client.Do(req)◀15 if err != nil {16 return 0, fmt.Errorf("do request: %w", err)17 }18 19 return resp.StatusCode, nil20 }
14行目response body must be closed
指摘されない
1 import (2 "context"3 "fmt"4 "net/http"5 )6 7 // HealthStatus はヘルスチェックのステータスコードを返す。8 func HealthStatus(ctx context.Context, client *http.Client) (int, error) {9 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/health", http.NoBody)10 if err != nil {11 return 0, fmt.Errorf("new request: %w", err)12 }13 14 resp, err := client.Do(req)15 if err != nil {16 return 0, fmt.Errorf("do request: %w", err)17 }18 19+ defer resp.Body.Close()20+空行21 return resp.StatusCode, nil22 }
bodyclose — HTTP レスポンスの Body を閉じ忘れている箇所を検出する。
指摘される
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は全ユーザーの名前を返す。8 func Names(ctx context.Context, db *sql.DB) ([]string, error) {9 rows, err := db.QueryContext(ctx, "SELECT name FROM users")◀10 if err != nil {11 return nil, fmt.Errorf("query names: %w", err)12 }13 14 var names []string15 16 for rows.Next() {17 var n string18 if err := rows.Scan(&n); err != nil {19 return nil, fmt.Errorf("scan name: %w", err)20 }21 22 names = append(names, n)23 }24 25 if err := rows.Err(); err != nil {26 return nil, fmt.Errorf("iterate names: %w", err)27 }28 29 return names, nil30 }
9行目Rows/Stmt/NamedStmt was not closed
指摘されない
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は全ユーザーの名前を返す。8 func Names(ctx context.Context, db *sql.DB) ([]string, error) {9 rows, err := db.QueryContext(ctx, "SELECT name FROM users")10 if err != nil {11 return nil, fmt.Errorf("query names: %w", err)12 }13+空行14+ defer rows.Close()15 16 var names []string17 18 for rows.Next() {19 var n string20 if err := rows.Scan(&n); err != nil {21 return nil, fmt.Errorf("scan name: %w", err)22 }23 24 names = append(names, n)25 }26 27 if err := rows.Err(); err != nil {28 return nil, fmt.Errorf("iterate names: %w", err)29 }30 31 return names, nil32 }
sqlclosecheck — *sql.Rows / *sql.Stmt の Close 忘れを検出する。
指摘される
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は全ユーザーの名前を返す。8 func Names(ctx context.Context, db *sql.DB) ([]string, error) {9 rows, err := db.QueryContext(ctx, "SELECT name FROM users")◀10 if err != nil {11 return nil, fmt.Errorf("query names: %w", err)12 }13 14 defer rows.Close()15 16 var names []string17 18 for rows.Next() {19 var n string20 if err := rows.Scan(&n); err != nil {21 return nil, fmt.Errorf("scan name: %w", err)22 }23 24 names = append(names, n)25 }26 27 return names, nil28 }
9行目rows.Err must be checked
指摘されない
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は全ユーザーの名前を返す。8 func Names(ctx context.Context, db *sql.DB) ([]string, error) {9 rows, err := db.QueryContext(ctx, "SELECT name FROM users")10 if err != nil {11 return nil, fmt.Errorf("query names: %w", err)12 }13 14 defer rows.Close()15 16 var names []string17 18 for rows.Next() {19 var n string20 if err := rows.Scan(&n); err != nil {21 return nil, fmt.Errorf("scan name: %w", err)22 }23 24 names = append(names, n)25 }26 27+ if err := rows.Err(); err != nil {28+ return nil, fmt.Errorf("iterate names: %w", err)29+ }30+空行31 return names, nil32 }
rowserrcheck — rows.Next() のループ後に rows.Err() を確認しているかを検出する。
指摘される
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // FindName は ID からユーザー名を返す。8 func FindName(ctx context.Context, db *sql.DB, id string) (string, error) {9− var gotID, name string10 11− err := db.QueryRowContext(ctx, "SELECT * FROM users WHERE id = $1", id).Scan(&gotID, &name)◀12 if err != nil {13 return "", fmt.Errorf("select user: %w", err)14 }15 16 return name, nil17 }
11行目avoid SELECT * - explicitly specify needed columns for better performance, maintainability and stability
指摘されない
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // FindName は ID からユーザー名を返す。8 func FindName(ctx context.Context, db *sql.DB, id string) (string, error) {9+ var name string10 11+ err := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)12 if err != nil {13 return "", fmt.Errorf("select user: %w", err)14 }15 16 return name, nil17 }
unqueryvet — SQL の SELECT * を検出する。取得する列を明示し、テーブル変更で Scan が壊れないようにする。
指摘される
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は ID の一覧からユーザー名を集める。8 func Names(ctx context.Context, db *sql.DB, ids []string) ([]string, error) {9 names := []string{}10 11− for _, id := range ids {12 var name string13 14− err := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)◀15− if err != nil {16− return nil, fmt.Errorf("select user: %w", err)17 }18 19 names = append(names, name)20 }21 22 return names, nil23 }
14行目[critical] potential N+1 query: QueryRowContext() called inside loop - Consider using a batch query with IN clause or JOIN
Suggestion: Collect all IDs before the loop, then use a single query with IN clause:
ids := make([]int, 0, len(items))
for _, item := range items { ids = append(ids, item.ID) }
db.Query("SELECT * FROM table WHERE id IN (?)", ids)
指摘されない
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Names は ID の一覧からユーザー名を集める。8 func Names(ctx context.Context, db *sql.DB, ids []string) ([]string, error) {9+ rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE id = ANY($1)", ids)10+ if err != nil {11+ return nil, fmt.Errorf("select users: %w", err)12+ }13+ defer rows.Close()14+空行15 names := []string{}16 17+ for rows.Next() {18 var name string19 20+ if err := rows.Scan(&name); err != nil {21+ return nil, fmt.Errorf("scan user: %w", err)22 }23 24 names = append(names, name)25 }26 27+ if err := rows.Err(); err != nil {28+ return nil, fmt.Errorf("iterate users: %w", err)29+ }30+空行31 return names, nil32 }
unqueryvet — SQL の SELECT * を検出する。取得する列を明示し、テーブル変更で Scan が壊れないようにする。
指摘される
1 import (2 "context"3 "database/sql"4 "fmt"5 )6 7 // Rename はユーザー名を変更する。8−func Rename(ctx context.Context, db *sql.DB, id, name string) error {9 tx, err := db.BeginTx(ctx, nil)◀10 if err != nil {11 return fmt.Errorf("begin tx: %w", err)12 }13 14− if _, err := tx.ExecContext(ctx, "UPDATE users SET name = $1 WHERE id = $2", name, id); err != nil {15 return fmt.Errorf("update user: %w", err)16 }17 18 return nil19 }
9行目[critical] unclosed transaction: tx - missing both Commit() and Rollback()
Suggestion: Add defer tx.Rollback() immediately after Begin(), then call Commit() on success
指摘されない
1 import (2 "context"3 "database/sql"4+ "errors"5 "fmt"6 )7 8 // Rename はユーザー名を変更する。9+func Rename(ctx context.Context, db *sql.DB, id, name string) (err error) {10 tx, err := db.BeginTx(ctx, nil)11 if err != nil {12 return fmt.Errorf("begin tx: %w", err)13 }14 15+ defer func() {16+ if err == nil {17+ return18+ }19+空行20+ if rbErr := tx.Rollback(); rbErr != nil {21+ err = errors.Join(err, fmt.Errorf("rollback: %w", rbErr))22+ }23+ }()24+空行25+ if _, err = tx.ExecContext(ctx, "UPDATE users SET name = $1 WHERE id = $2", name, id); err != nil {26 return fmt.Errorf("update user: %w", err)27+ }28+空行29+ if err = tx.Commit(); err != nil {30+ return fmt.Errorf("commit: %w", err)31 }32 33 return nil34 }
unqueryvet — SQL の SELECT * を検出する。取得する列を明示し、テーブル変更で Scan が壊れないようにする。
指摘される
1 import "log/slog"2 3 // LogStarted は起動ログを出す。4 func LogStarted(addr string) {5− slog.Info("server started", slog.String("addr", addr))◀6 }
5行目attributes should not be used
指摘されない
1 import "log/slog"2 3 // LogStarted は起動ログを出す。4 func LogStarted(addr string) {5+ slog.Info("server started", "addr", addr)6 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import "log/slog"2 3 // LogCreated はユーザー作成をログに出す。4 func LogCreated(id string) {5− slog.Info("user created", "userID", id)◀6 }
5行目keys should be written in snake_case
指摘されない
1 import "log/slog"2 3 // LogCreated はユーザー作成をログに出す。4 func LogCreated(id string) {5+ slog.Info("user created", "user_id", id)6 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import "log/slog"2 3 // LogDeleted は削除ログを出す。4 func LogDeleted(id string) {5− slog.Info("user deleted: " + id)◀6 }
5行目message should be a string literal or a constant
指摘されない
1 import "log/slog"2 3 // LogDeleted は削除ログを出す。4 func LogDeleted(id string) {5+ slog.Info("user deleted", "user_id", id)6 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import (2 "context"3 "log/slog"4 )5 6 // Process は処理してログを出す。7 func Process(ctx context.Context, id string) {8− slog.Info("processing", "user_id", id)◀9 }
8行目InfoContext should be used instead
revive も同じ箇所を指摘します
指摘されない
1 import (2 "context"3 "log/slog"4 )5 6 // Process は処理してログを出す。7 func Process(ctx context.Context, id string) {8+ slog.InfoContext(ctx, "processing", "user_id", id)9 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import "log/slog"2 3 // LogFailure は失敗を記録する。4 func LogFailure(detail string) {5− slog.Error("request failed", "msg", detail)◀6 }
5行目the "msg" key is forbidden and should not be used
指摘されない
1 import "log/slog"2 3 // LogFailure は失敗を記録する。4 func LogFailure(detail string) {5+ slog.Error("request failed", "detail", detail)6 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import (2 "context"3 "log/slog"4 )5 6 // Started はサーバーの起動を記録する。7 func Started(ctx context.Context, addr string) {8− slog.InfoContext(ctx, "Server started", "addr", addr)◀9 }
8行目message should be lowercased
指摘されない
1 import (2 "context"3 "log/slog"4 )5 6 // Started はサーバーの起動を記録する。7 func Started(ctx context.Context, addr string) {8+ slog.InfoContext(ctx, "server started", "addr", addr)9 }
sloglint — log/slog の書き方を揃える。引数はキーと値のペア、キーは snake_case、メッセージは固定文字列、context がある場所では *Context 関数を使う。 設定: kv-only: true / key-naming-case: snake / static-msg: true / context: scope / forbidden-keys: [time, level, msg, source] / msg-style: lowercased
指摘される
1 import "time"2 3 // UserResponse はユーザー API の応答。4 type UserResponse struct {5 ID string `json:"id"`6− CreatedAt time.Time `json:"createdAt"`◀7 }
6行目json(snake): got 'createdAt' want 'created_at'
指摘されない
1 import "time"2 3 // UserResponse はユーザー API の応答。4 type UserResponse struct {5 ID string `json:"id"`6+ CreatedAt time.Time `json:"created_at"`7 }
tagliatelle — 構造体タグの名前の形式を揃える。JSON は snake_case(既存の created_at と api/openapi.yaml に合わせる)。 設定: case.rules.json: snake / case.use-field-name: true
指摘される
1 // UserResponse はユーザーの応答。2 type UserResponse struct {3− UserName string `json:"name"`◀4 }
3行目json(snake): got 'name' want 'user_name'
指摘されない
1 // UserResponse はユーザーの応答。2 type UserResponse struct {3+ UserName string `json:"user_name"`4 }
tagliatelle — 構造体タグの名前の形式を揃える。JSON は snake_case(既存の created_at と api/openapi.yaml に合わせる)。 設定: case.rules.json: snake / case.use-field-name: true
指摘される
1 // CreateUserRequest はユーザー作成の入力。2 type CreateUserRequest struct {3− Name string `validate:"required" json:"name"`◀4 Email string `json:"email" validate:"required,email"`5 }
3行目File is not properly formatted
tagalign も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは golines のメッセージです。
指摘されない
1 // CreateUserRequest はユーザー作成の入力。2 type CreateUserRequest struct {3+ Name string `json:"name" validate:"required"`4 Email string `json:"email" validate:"required,email"`5 }
tagalign — 構造体タグの並び順と位置を揃える。
指摘される
1 import (2 "encoding/json"3 "fmt"4 "time"5 )6 7 // Event は通知イベント。8 type Event struct {9− Name string10− CreatedAt time.Time11 }12 13 // Encode はイベントを JSON にする。14 func Encode(e Event) ([]byte, error) {15 b, err := json.Marshal(e)◀16 if err != nil {17 return nil, fmt.Errorf("marshal event: %w", err)18 }19 20 return b, nil21 }
15行目the given struct should be annotated with the `json` tag
指摘されない
1 import (2 "encoding/json"3 "fmt"4 "time"5 )6 7 // Event は通知イベント。8 type Event struct {9+ Name string `json:"name"`10+ CreatedAt time.Time `json:"created_at"`11 }12 13 // Encode はイベントを JSON にする。14 func Encode(e Event) ([]byte, error) {15 b, err := json.Marshal(e)16 if err != nil {17 return nil, fmt.Errorf("marshal event: %w", err)18 }19 20 return b, nil21 }
musttag — json.Marshal などに渡す構造体のフィールドに、タグが付いているかを検出する。
指摘される
1 import (2 "encoding/json"3 "io"4 )5 6 // WriteJSON は v を JSON で書き出す。7 func WriteJSON(w io.Writer, v any) {8− json.NewEncoder(w).Encode(v) //nolint◀9 }
8行目directive `//nolint` should mention specific linter such as `//nolint:my-linter`
指摘されない
1 import (2 "encoding/json"3 "io"4 )5 6 // WriteJSON は v を JSON で書き出す。7 func WriteJSON(w io.Writer, v any) {8+ json.NewEncoder(w).Encode(v) //nolint:errcheck // 送信失敗はクライアント切断なので無視する9 }
nolintlint — //nolint を書くときは、止めるリンター名と理由を必ず書かせる。 設定: allow-unused: false / require-explanation: true / require-specific: true
指摘される
1 // Add は足し算をする。2−func Add(a, b int) int { //nolint:mnd // 以前は 2 を掛けていた◀3 return a + b4 }
2行目directive `//nolint:mnd // 以前は 2 を掛けていた` is unused for linter "mnd"
指摘されない
1 // Add は足し算をする。2+func Add(a, b int) int {3 return a + b4 }
nolintlint — //nolint を書くときは、止めるリンター名と理由を必ず書かせる。 設定: allow-unused: false / require-explanation: true / require-specific: true
指摘される
1 import "testing"2 3 // AssertEqual は 2 つの文字列が等しいことを確かめる。4 func AssertEqual(t *testing.T, got, want string) {◀5 if got != want {6 t.Errorf("got %q, want %q", got, want)7 }8 }
4行目test helper function should start from t.Helper()
指摘されない
1 import "testing"2 3 // AssertEqual は 2 つの文字列が等しいことを確かめる。4 func AssertEqual(t *testing.T, got, want string) {5+ t.Helper()6+空行7 if got != want {8 t.Errorf("got %q, want %q", got, want)9 }10 }
thelper — テストヘルパーの先頭で t.Helper() を呼ばせ、失敗時に呼び出し元の行が表示されるようにする。
指摘される
1 import (2 "strings"3 "testing"4 )5 6 func TestUpper(t *testing.T) {◀7 tests := []struct{ in, want string }{{"go", "GO"}}8 for _, tt := range tests {9 t.Run(tt.in, func(t *testing.T) {10 t.Parallel()11 12 if got := strings.ToUpper(tt.in); got != tt.want {13 t.Errorf("got %q, want %q", got, tt.want)14 }15 })16 }17 }
6行目Function TestUpper missing the call to method parallel
tparallel も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは paralleltest のメッセージです。
指摘されない
1 import (2 "strings"3 "testing"4 )5 6 func TestUpper(t *testing.T) {7+ t.Parallel()8+空行9 tests := []struct{ in, want string }{{"go", "GO"}}10 for _, tt := range tests {11 t.Run(tt.in, func(t *testing.T) {12 t.Parallel()13 14 if got := strings.ToUpper(tt.in); got != tt.want {15 t.Errorf("got %q, want %q", got, tt.want)16 }17 })18 }19 }
tparallel — サブテストだけ t.Parallel() を呼び、親のテストで呼んでいないといった不揃いを検出する。
指摘される
1 import (2 "os"3 "testing"4 )5 6 func TestAddr(t *testing.T) {7− os.Setenv("APP_ADDR", ":0")◀8 9 if got := os.Getenv("APP_ADDR"); got != ":0" {10 t.Errorf("got %q", got)11 }12 }
7行目os.Setenv() could be replaced by t.Setenv() in TestAddr
paralleltest も同じ箇所を指摘します
指摘されない
1 import (2 "os"3 "testing"4 )5 6 func TestAddr(t *testing.T) {7+ t.Setenv("APP_ADDR", ":0")8 9 if got := os.Getenv("APP_ADDR"); got != ":0" {10 t.Errorf("got %q", got)11 }12 }
usetesting — テストで os.Setenv / os.MkdirTemp / context.Background ではなく、t.Setenv / t.TempDir / t.Context を使わせる(v1 の tenv の後継)。 設定: context-background / context-todo / os-temp-dir: true
指摘される
1−import (2− "context"3− "testing"4−)5 6 func TestDeadline(t *testing.T) {7 t.Parallel()8 9− ctx := context.Background()◀10 if _, ok := ctx.Deadline(); ok {11 t.Fatal("deadline is set")12 }13 }
9行目context.Background() could be replaced by t.Context() in TestDeadline
指摘されない
1+import "testing"2 3 func TestDeadline(t *testing.T) {4 t.Parallel()5 6+ ctx := t.Context()7 if _, ok := ctx.Deadline(); ok {8 t.Fatal("deadline is set")9 }10 }
usetesting — テストで os.Setenv / os.MkdirTemp / context.Background ではなく、t.Setenv / t.TempDir / t.Context を使わせる(v1 の tenv の後継)。 設定: context-background / context-todo / os-temp-dir: true
指摘される
1 import (2 "os"3 "path/filepath"4 "testing"5 )6 7 func TestWriteFile(t *testing.T) {8 t.Parallel()9 10− path := filepath.Join(os.TempDir(), "out.txt")◀11 if err := os.WriteFile(path, []byte("ok"), 0o600); err != nil {12 t.Fatal(err)13 }14 }
10行目os.TempDir() could be replaced by t.TempDir() in TestWriteFile
指摘されない
1 import (2 "os"3 "path/filepath"4 "testing"5 )6 7 func TestWriteFile(t *testing.T) {8 t.Parallel()9 10+ path := filepath.Join(t.TempDir(), "out.txt")11 if err := os.WriteFile(path, []byte("ok"), 0o600); err != nil {12 t.Fatal(err)13 }14 }
usetesting — テストで os.Setenv / os.MkdirTemp / context.Background ではなく、t.Setenv / t.TempDir / t.Context を使わせる(v1 の tenv の後継)。 設定: context-background / context-todo / os-temp-dir: true
指摘される
1 import "testing"2 3 func TestDouble(t *testing.T) {◀4 tests := []struct {5 name string6 in int7 want int8 }{9 {name: "zero", in: 0, want: 0},10 {name: "one", in: 1, want: 2},11 }12 for _, tt := range tests {◀13 t.Run(tt.name, func(t *testing.T) {14 if got := tt.in + tt.in; got != tt.want {15 t.Errorf("got %d, want %d", got, tt.want)16 }17 })18 }19 }
3行目Function TestDouble missing the call to method parallel
12行目Range statement for test TestDouble missing the call to method parallel in test Run
指摘されない
1 import "testing"2 3 func TestDouble(t *testing.T) {4+ t.Parallel()5+空行6 tests := []struct {7 name string8 in int9 want int10 }{11 {name: "zero", in: 0, want: 0},12 {name: "one", in: 1, want: 2},13 }14 for _, tt := range tests {15 t.Run(tt.name, func(t *testing.T) {16+ t.Parallel()17+空行18 if got := tt.in + tt.in; got != tt.want {19 t.Errorf("got %d, want %d", got, tt.want)20 }21 })22 }23 }
paralleltest — すべてのテストとサブテストで t.Parallel() を呼ばせる。並行に動かして、テスト間で状態を共有するバグに早く気づく。
指摘される
1 import (2 "fmt"3 "strings"4 )5 6 func Example() {◀7 fmt.Println(strings.ToUpper("go"))8 }
6行目missing output for example, go test can't validate it
指摘されない
1 import (2 "fmt"3 "strings"4 )5 6 func Example() {7 fmt.Println(strings.ToUpper("go"))8+ // Output: GO9 }
testableexamples — Example テストに // Output: があり、実際に検証されるかを確認する。
指摘される
1 import (2 "fmt"3 "os"4 )5 6 // ReadConfig は設定ファイルを読む。7 func ReadConfig(path string) ([]byte, error) {8 b, err := os.ReadFile(path)9−空行◀10 if err != nil {11 return nil, fmt.Errorf("read config: %w", err)12 }13 14 return b, nil15 }
9行目File is not properly formatted
指摘されない
1 import (2 "fmt"3 "os"4 )5 6 // ReadConfig は設定ファイルを読む。7 func ReadConfig(path string) ([]byte, error) {8 b, err := os.ReadFile(path)9 if err != nil {10 return nil, fmt.Errorf("read config: %w", err)11 }12 13 return b, nil14 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 import "strings"2 3 // Title は先頭を大文字にする。4 func Title(s string) string {5− var trimmed = strings.TrimSpace(s)◀6 7 return strings.ToUpper(trimmed[:1]) + trimmed[1:]8 }
5行目File is not properly formatted
指摘されない
1 import "strings"2 3 // Title は先頭を大文字にする。4 func Title(s string) string {5+ trimmed := strings.TrimSpace(s)6 7 return strings.ToUpper(trimmed[:1]) + trimmed[1:]8 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1−//MaxNameLength は名前の最大文字数。◀2 const MaxNameLength = 50
1行目commentFormatting: put a space between `//` and comment text
gofumpt も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは gocritic のメッセージです。
指摘されない
1+// MaxNameLength は名前の最大文字数。2 const MaxNameLength = 50
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 import (2 "fmt"3 "os"4 )5 6 // ConfigFileMode は設定ファイルの権限。7−const ConfigFileMode = 0600◀8 9 // Save はファイルを書き出す。10 func Save(path string, b []byte) error {11 if err := os.WriteFile(path, b, ConfigFileMode); err != nil {12 return fmt.Errorf("write config: %w", err)13 }14 15 return nil16 }
7行目octalLiteral: use new octal literal style, 0o600
gofumpt も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは gocritic のメッセージです。
指摘されない
1 import (2 "fmt"3 "os"4 )5 6 // ConfigFileMode は設定ファイルの権限。7+const ConfigFileMode = 0o6008 9 // Save はファイルを書き出す。10 func Save(path string, b []byte) error {11 if err := os.WriteFile(path, b, ConfigFileMode); err != nil {12 return fmt.Errorf("write config: %w", err)13 }14 15 return nil16 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 // User はユーザー。2 type User struct {3 Name string4 Age int5 }6 7 // Guest はゲストユーザー。8−var Guest = User{Name: "guest",◀9− Age: 0}
8行目File is not properly formatted
指摘されない
1 // User はユーザー。2 type User struct {3 Name string4 Age int5 }6 7 // Guest はゲストユーザー。8+var Guest = User{9+ Name: "guest",10+ Age: 0,11+}
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 // Marker は目印用の型。2−type Marker struct {◀3−}
2行目File is not properly formatted
指摘されない
1 // Marker は目印用の型。2+type Marker struct{}
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1−var (◀2− // DefaultLimit は一覧取得の既定件数。3− DefaultLimit = 204−)
1行目File is not properly formatted
指摘されない
1+// DefaultLimit は一覧取得の既定件数。2+var DefaultLimit = 20
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 // Min は小さいほうを返す。2 func Min(a, b int) int {3 return min(a, b)4 }◀5 // Max は大きいほうを返す。6 func Max(a, b int) int {7 return max(a, b)8 }
4行目File is not properly formatted
整形ツールはまとめて実行されるため、gofumpt の対象でも gofmt の名前で表示されることがあります。make fmt で直ります。
指摘されない
1 // Min は小さいほうを返す。2 func Min(a, b int) int {3 return min(a, b)4 }5+空行6 // Max は大きいほうを返す。7 func Max(a, b int) int {8 return max(a, b)9 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
gofumpt · 整形 · make fmt で自動修正
同じ型が続く引数はまとめる(extra-rules)
extra-rules: true で有効になるルール。w int, h int は w, h int と書く。
指摘される
1 // Area は長方形の面積を返す。2−func Area(w int, h int) int {◀3 return w * h4 }
2行目paramTypeCombine: func(w int, h int) int could be replaced with func(w, h int) int
gofumpt も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは gocritic のメッセージです。
指摘されない
1 // Area は長方形の面積を返す。2+func Area(w, h int) int {3 return w * h4 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
gofumpt · 整形 · make fmt で自動修正
不要なブランク識別子を書かない(gofmt -s)
gofumpt は gofmt -s の簡略化も行う。range でインデックスだけ使うなら i, _ ではなく i と書く。
指摘される
1 // Indexes は添字の一覧を返す。2 func Indexes(names []string) []int {3 out := make([]int, 0, len(names))4− for i, _ := range names {◀5 out = append(out, i)6 }7 8 return out9 }
4行目File is not properly formatted
整形ツールはまとめて実行されるため、gofumpt の対象でも gofmt の名前で表示されることがあります。make fmt で直ります。
指摘されない
1 // Indexes は添字の一覧を返す。2 func Indexes(names []string) []int {3 out := make([]int, 0, len(names))4+ for i := range names {5 out = append(out, i)6 }7 8 return out9 }
gofumpt — gofmt より厳しい整形ルール。gofmt の整形を含む(gofmt は書き換えルールのためだけに併用している)。v2 では formatters に分かれ、make fmt(golangci-lint fmt)で整形する。 設定: extra.group-params: true
指摘される
1 // Tail は先頭を除いた残りを返す。2−func Tail(s []int) []int { return s[1:len(s)] }◀
2行目File is not properly formatted
指摘されない
1 // Tail は先頭を除いた残りを返す。2+func Tail(s []int) []int { return s[1:] }
gofmt — make fmt で interface{} を any に、s[a:len(s)] を s[a:] に自動で書き換える(gofumpt と併用)。 設定: rewrite-rules: interface{} → any / a[b:len(a)] → a[b:]
指摘される
1 import (2 "example.com/go-clean/internal/domain/user"◀3− "context"4 )5 6 // FindName はユーザー名を探す。7 func FindName(_ context.Context) string {8 return user.DefaultName9 }
2行目File is not properly formatted
整形ツールはまとめて実行されるため、goimports の対象でも gofmt の名前で表示されることがあります。make fmt で直ります。
指摘されない
1 import (2+ "context"3+空行4 "example.com/go-clean/internal/domain/user"5 )6 7 // FindName はユーザー名を探す。8 func FindName(_ context.Context) string {9 return user.DefaultName10 }
goimports — import の並びとグループ分けを揃える。自モジュール(example.com/go-clean)は独立したグループにする。 設定: local-prefixes: [example.com/go-clean]
指摘される
1 // Greet は挨拶文を返す。2 func Greet(name string) string {◀3−空行4 return "Hello, " + name5 }
2行目unnecessary leading newline
gofumpt も同じ箇所を指摘します
指摘されない
1 // Greet は挨拶文を返す。2 func Greet(name string) string {3 return "Hello, " + name4 }
whitespace — 関数や if / for などのブロックの先頭・末尾にある不要な空行を検出する。
指摘される
1 // TotalLength は文字数の合計を返す。2 func TotalLength(names []string) int {3 total := 04 for _, n := range names {5 total += len(n)6 total++7−空行8 }◀9 10 return total11 }
8行目unnecessary trailing newline
wsl_v5 も同じ箇所を指摘します
指摘されない
1 // TotalLength は文字数の合計を返す。2 func TotalLength(names []string) int {3 total := 04 for _, n := range names {5 total += len(n)6 total++7 }8 9 return total10 }
whitespace — 関数や if / for などのブロックの先頭・末尾にある不要な空行を検出する。
指摘される
1 import "net/http"2 3 // Recorder はステータスコードを記録する ResponseWriter。4 type Recorder struct {5 http.ResponseWriter◀6 Status int7 }8 9 // WriteHeader はステータスコードを記録してから書き込む。10 func (r *Recorder) WriteHeader(status int) {11 r.Status = status12 r.ResponseWriter.WriteHeader(status)13 }
5行目there must be an empty line separating embedded fields from regular fields
指摘されない
1 import "net/http"2 3 // Recorder はステータスコードを記録する ResponseWriter。4 type Recorder struct {5 http.ResponseWriter6+空行7 Status int8 }9 10 // WriteHeader はステータスコードを記録してから書き込む。11 func (r *Recorder) WriteHeader(status int) {12 r.Status = status13 r.ResponseWriter.WriteHeader(status)14 }
embeddedstructfieldcheck — 構造体の埋め込みフィールドを先頭に置き、通常のフィールドとの間に空行を入れる。 設定: empty-line: true
指摘される
1 // FirstError は最初のエラーを返す。2 func FirstError(a, b error) error {3 if a != nil {4 return a5 }6 if b != nil {◀7 return b8 }9 10 return nil11 }
6行目missing whitespace above this line (invalid statement above if)
指摘されない
1 // FirstError は最初のエラーを返す。2 func FirstError(a, b error) error {3 if a != nil {4 return a5 }6+空行7 if b != nil {8 return b9 }10 11 return nil12 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import "strings"2 3 // SameName は前後の空白を除いて比較する。4 func SameName(a, b string) bool {5 x := strings.TrimSpace(a)6 y := strings.TrimSpace(b)◀7 if x == y {8 return true9 }10 11 return strings.EqualFold(x, y)12 }
6行目missing whitespace above this line (too many statements above if)
指摘されない
1 import "strings"2 3 // SameName は前後の空白を除いて比較する。4 func SameName(a, b string) bool {5 x := strings.TrimSpace(a)6+空行7 y := strings.TrimSpace(b)8 if x == y {9 return true10 }11 12 return strings.EqualFold(x, y)13 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import "strings"2 3 // Initials は頭文字をつなげて返す。4 func Initials(words []string) string {5 var b strings.Builder6 for _, w := range words {7 b.WriteString(w[:1])8 }9 return b.String()◀10 }
9行目missing whitespace above this line (too many lines above return)
指摘されない
1 import "strings"2 3 // Initials は頭文字をつなげて返す。4 func Initials(words []string) string {5 var b strings.Builder6 for _, w := range words {7 b.WriteString(w[:1])8 }9+空行10 return b.String()11 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
wsl_v5 · 空行 · 手で修正
代入はブロックの直後に続けない
代入の直前にくっつけてよいのは、別の代入だけ。
指摘される
1 import "strings"2 3 // Slug は URL 用の文字列を作る。4 func Slug(title string) string {5 if title == "" {6 return ""7 }8 lower := strings.ToLower(title)◀9 10 return strings.ReplaceAll(lower, " ", "-")11 }
8行目missing whitespace above this line (invalid statement above assign)
指摘されない
1 import "strings"2 3 // Slug は URL 用の文字列を作る。4 func Slug(title string) string {5 if title == "" {6 return ""7 }8+空行9 lower := strings.ToLower(title)10 11 return strings.ReplaceAll(lower, " ", "-")12 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
wsl_v5 · 空行 · 手で修正
関数呼び出しなどの式はブロックの直後に続けない
ブロックの処理と、その後の処理を空行で区切る。
指摘される
1 import "log/slog"2 3 // Run は処理を実行してログを出す。4 func Run(steps []func() error) {5 for _, step := range steps {6 if err := step(); err != nil {7 slog.Error("step failed", "error", err)8 }9 }10 slog.Info("all steps finished")◀11 }
10行目missing whitespace above this line (invalid statement above expr)
指摘されない
1 import "log/slog"2 3 // Run は処理を実行してログを出す。4 func Run(steps []func() error) {5 for _, step := range steps {6 if err := step(); err != nil {7 slog.Error("step failed", "error", err)8 }9 }10+空行11 slog.Info("all steps finished")12 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import "log/slog"2 3 // Start は開始ログを出して名前を返す。4 func Start(name string) string {5 label := "[" + name + "]"6− slog.Info("start")◀7 8 return label9 }
6行目missing whitespace above this line (no shared variables above expr)
指摘されない
1 import "log/slog"2 3 // Start は開始ログを出して名前を返す。4 func Start(name string) string {5 label := "[" + name + "]"6+ slog.Info("start", "label", label)7 8 return label9 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // Average は平均を返す。2 func Average(nums []int) float64 {3 count := len(nums)4 var sum int◀5 for _, n := range nums {6 sum += n7 }8 9 return float64(sum) / float64(count)10 }
4行目missing whitespace above this line (never cuddle decl)
指摘されない
1 // Average は平均を返す。2 func Average(nums []int) float64 {3 count := len(nums)4+空行5 var sum int6 for _, n := range nums {7 sum += n8 }9 10 return float64(sum) / float64(count)11 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // Sum は合計とラベルを返す。2 func Sum(nums []int) (int, string) {3 total := 04−空行5− label := "sum"6 for _, n := range nums {◀7 total += n8 }9 10 return total, label11 }
6行目missing whitespace above this line (no shared variables above range)
指摘されない
1 // Sum は合計とラベルを返す。2 func Sum(nums []int) (int, string) {3+ label := "sum"4+空行5 total := 06 for _, n := range nums {7 total += n8 }9 10 return total, label11 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import (2 "context"3 "time"4 )5 6 // WithDeadline は呼び出し元のキャンセルを引き継がず、期限付きで fn を実行する。7 func WithDeadline(ctx context.Context, fn func(context.Context) error) error {8 base := context.WithoutCancel(ctx)9 ctx, cancel := context.WithTimeout(base, time.Second)◀10 defer cancel()11 12 return fn(ctx)13 }
9行目missing whitespace above this line (too many statements above defer)
指摘されない
1 import (2 "context"3 "time"4 )5 6 // WithDeadline は呼び出し元のキャンセルを引き継がず、期限付きで fn を実行する。7 func WithDeadline(ctx context.Context, fn func(context.Context) error) error {8 base := context.WithoutCancel(ctx)9+空行10 ctx, cancel := context.WithTimeout(base, time.Second)11 defer cancel()12 13 return fn(ctx)14 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // Tags はタグ一覧を作る。2 func Tags(base []string, extra string) []string {3 tags := base4 suffix := "!"5− tags = append(tags, extra)◀6 7 return append(tags, suffix)8 }
5行目missing whitespace above this line (no shared variables above append)
指摘されない
1 // Tags はタグ一覧を作る。2 func Tags(base []string, extra string) []string {3 tags := base4+ tags = append(tags, extra)5+空行6 suffix := "!"7 8 return append(tags, suffix)9 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // 評価の境界となる点数。2 const (3 GradeA = 804 GradeB = 605 )6 7 // Grade は点数から評価を返す。8 func Grade(score int) string {9 label := "C"10 switch {◀11 case score >= GradeA:12 return "A"13 case score >= GradeB:14 return "B"15 }16 17 return label18 }
10行目missing whitespace above this line (no shared variables above switch)
指摘されない
1 // 評価の境界となる点数。2 const (3 GradeA = 804 GradeB = 605 )6 7 // Grade は点数から評価を返す。8 func Grade(score int) string {9 label := "C"10+空行11 switch {12 case score >= GradeA:13 return "A"14 case score >= GradeB:15 return "B"16 }17 18 return label19 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // CountUntilEmpty は空文字が出るまで数える。2 func CountUntilEmpty(names []string) int {3 count := 04 5 for _, n := range names {6 if n == "" {7 count--8 count++9 break◀10 }11 12 count++13 }14 15 return count16 }
9行目missing whitespace above this line (too many lines above branch)
指摘されない
1 // CountUntilEmpty は空文字が出るまで数える。2 func CountUntilEmpty(names []string) int {3 count := 04 5 for _, n := range names {6 if n == "" {7 count--8 count++9+空行10 break11 }12 13 count++14 }15 16 return count17 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 // StartWorkers はワーカーを起動する。2 func StartWorkers(work func(int), n int) int {3 started := 04 go work(n)◀5 6 return started7 }
4行目missing whitespace above this line (no shared variables above go)
指摘されない
1 // StartWorkers はワーカーを起動する。2 func StartWorkers(work func(int), n int) int {3 started := 04+空行5 go work(n)6 7 return started8 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import (2 "log/slog"3 "time"4 )5 6 // Measure は fn の実行時間を記録して返す。7 func Measure(fn func()) time.Duration {8 start := time.Now()9 10 fn()11 elapsed := time.Since(start)◀12 13 slog.Info("measured", "elapsed", elapsed)14 15 return elapsed16 }
11行目missing whitespace above this line (invalid statement above assign)
指摘されない
1 import (2 "log/slog"3 "time"4 )5 6 // Measure は fn の実行時間を記録して返す。7 func Measure(fn func()) time.Duration {8 start := time.Now()9 10 fn()11+空行12 elapsed := time.Since(start)13 14 slog.Info("measured", "elapsed", elapsed)15 16 return elapsed17 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import "strings"2 3 // Label は状態の表示名を返す。4 func Label(status string) string {5 switch status {6 case "active":7 label := strings.ToUpper(status)8 suffix := " (can login)"9 10 return label + suffix◀11 case "locked":12 return "LOCKED"13 default:14 return "UNKNOWN"15 }16 }
10行目missing whitespace below this line (case-trailing-newline)
指摘されない
1 import "strings"2 3 // Label は状態の表示名を返す。4 func Label(status string) string {5 switch status {6 case "active":7 label := strings.ToUpper(status)8 suffix := " (can login)"9 10 return label + suffix11+空行12 case "locked":13 return "LOCKED"14 default:15 return "UNKNOWN"16 }17 }
wsl_v5 — 文の種類ごとに「直前の行とくっつけてよいか(cuddle)」を決め、空行で処理のまとまりを区切らせる。v2 では wsl(v4)が非推奨になり wsl_v5 に置き換わった。 設定: allow-first-in-block: true / allow-whole-block: false / branch-max-lines: 2 / case-max-lines: 3 / enable: [assign-expr]
指摘される
1 import "log/slog"2 3 // LogRequest はリクエストの情報をログに出す。4 func LogRequest(method, path, userAgent, remoteAddr string, status int) {5− slog.Info("request completed", "method", method, "path", path, "user_agent", userAgent, "remote_addr", remoteAddr, "status", status)◀6 }
5行目File is not properly formatted
lll も同じ箇所を指摘します。同じ行の指摘は 1 件にまとめられるため、表示されるのは golines のメッセージです。
指摘されない
1 import "log/slog"2 3 // LogRequest はリクエストの情報をログに出す。4 func LogRequest(method, path, userAgent, remoteAddr string, status int) {5+ slog.Info("request completed",6+ "method", method,7+ "path", path,8+ "user_agent", userAgent,9+ "remote_addr", remoteAddr,10+ "status", status,11+ )12 }
lll — 1 行の長さの上限。タブは 1 文字として数える。 設定: line-length: 120 / tab-width: 4
指摘される
1 import (2 "log/slog"3 "net/http"4 "time"5 )6 7 // LogRequest はリクエストの結果を記録する。8 func LogRequest(r *http.Request, status int, start time.Time) {9− slog.InfoContext(r.Context(), "request", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", time.Since(start).Milliseconds())◀10 }
9行目File is not properly formatted
指摘されない
1 import (2 "log/slog"3 "net/http"4 "time"5 )6 7 // LogRequest はリクエストの結果を記録する。8 func LogRequest(r *http.Request, status int, start time.Time) {9+ slog.InfoContext(10+ r.Context(),11+ "request",12+ "method",13+ r.Method,14+ "path",15+ r.URL.Path,16+ "status",17+ status,18+ "duration_ms",19+ time.Since(start).Milliseconds(),20+ )21 }
golines — 120 文字を超える行を make fmt で自動的に折り返す(整形ツール)。折り返し方が 1 通りに決まる。 設定: max-len: 120 / tab-len: 4(lll も tab-width: 4 に揃える)
指摘される
1 import "errors"2 3−// ErrUnexpected is returned when an unexpected error occured.◀4−var ErrUnexpected = errors.New("unexpected error occured")◀
3行目`occured` is a misspelling of `occurred`
4行目`occured` is a misspelling of `occurred`
指摘されない
1 import "errors"2 3+// ErrUnexpected is returned when an unexpected error occurred.4+var ErrUnexpected = errors.New("unexpected error occurred")
misspell — コメントや文字列中のよくある英単語のスペルミスを検出する。日本語は対象外。 設定: locale: US
指摘される
1−// Colour returns the theme colour.◀2−func Colour() string {◀3 return "blue"4 }
1行目`Colour` is a misspelling of `Color`
2行目`Colour` is a misspelling of `Color`
指摘されない
1+// Color returns the theme color.2+func Color() string {3 return "blue"4 }
misspell — コメントや文字列中のよくある英単語のスペルミスを検出する。日本語は対象外。 設定: locale: US