.cursorrules Go Backend

Goバックエンドベストプラクティス

Goバックエンド開発の包括的なcursorrules。イディオマティックGo、エラーハンドリング、テスト、並行処理パターン。

.cursorrules · 57 lines
You are an expert Go engineer focused on building idiomatic, performant, and maintainable backend services.

## Core Principles

- Write idiomatic Go. Follow the patterns established in the standard library.
- Errors are values — handle them explicitly. Never ignore `err`.
- Prefer composition over inheritance. Interfaces define behavior.
- Keep functions small and focused. Single responsibility.
- Concurrency via goroutines and channels — not shared memory.

## Error Handling

- Wrap errors with context: `fmt.Errorf("operation failed: %w", err)`
- Define sentinel errors with `errors.New()` for comparison.
- Use custom error types for rich error information.
- Always check errors immediately after the call.
- Log errors at the boundary (service layer), not in libraries.

## Code Style

- `gofmt` / `goimports` always.
- Keep cyclomatic complexity low — extract helpers aggressively.
- Avoid naked returns in long functions.
- Use named return values only for documentation, not assignment.
- Short variable declarations (`:=`) in function bodies.

## Testing

- Table-driven tests for comprehensive coverage.
- `testify/assert` for assertions.
- `httptest` for HTTP handler tests.
- Mock interfaces with `mockery` or manual stubs.
- Test file naming: `foo_test.go` in same package.

## Concurrency

- Channel direction matters: `chan<-` send-only, `<-chan` receive-only.
- `sync.WaitGroup` for fan-out patterns.
- `sync.Mutex` for shared state — minimize critical sections.
- `context.Context` for cancellation and deadlines — always first arg.
- Avoid goroutine leaks: always provide a stop mechanism.

## Project Layout

```
cmd/server/main.go    # Entry point
internal/             # Private packages
pkg/                  # Public packages
api/                  # OpenAPI specs, proto files
```

## HTTP Services

- Use `net/http` or `chi` for routing.
- Middleware for cross-cutting concerns (logging, auth, tracing).
- Always close `resp.Body`.
- Use `json.Decoder` over `json.Unmarshal` for streams.
Share on X

こちらもおすすめ

Backend カテゴリの他のルール

もっとルールを探す

CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 223 ルールをチェック。