claude-help

Phát triển dự án Golang với Claude Code CLI

Hướng dẫn toàn diện sử dụng Claude Code CLI để phát triển ứng dụng Go — từ khởi tạo dự án, xây dựng API, database, testing cho đến deploy.


1. Khởi tạo dự án Go

Tạo dự án mới từ đầu

mkdir my-go-project && cd my-go-project
claude
Tạo dự án Go với:
- go mod init github.com/username/my-go-project
- Gin framework cho REST API
- Clean architecture structure (cmd, internal, pkg)
- Makefile với các target: build, run, test, lint, migrate
- Dockerfile multi-stage build
- .env.example và config loader với Viper
- .gitignore cho Go

Khởi tạo với framework cụ thể

Gin Framework:

Khởi tạo dự án Go REST API với Gin framework:
- go mod init github.com/username/my-api
- Gin router với middleware logging, recovery, CORS
- Cấu trúc clean architecture
- Config loader từ .env bằng Viper
- Logger với zerolog
- Graceful shutdown

Echo Framework:

Khởi tạo dự án Go với Echo framework:
- go mod init github.com/username/my-echo-api
- Echo v4 với middleware chuẩn
- Swagger docs tự động với swaggo
- Validator với go-playground/validator
- Custom error handler

Fiber Framework:

Khởi tạo dự án Go với Fiber framework:
- go mod init github.com/username/my-fiber-api
- Fiber v2 với prefork mode
- Rate limiter middleware
- Template engine
- Static file serving
- WebSocket support

Tạo Makefile đầy đủ

Tạo Makefile cho dự án Go với các target:
- build: biên dịch binary
- run: chạy ứng dụng
- dev: chạy với air (hot reload)
- test: chạy tất cả tests
- test-cover: chạy test với coverage report
- lint: chạy golangci-lint
- migrate-up / migrate-down: quản lý migration
- docker-build / docker-run: Docker commands
- swagger: generate Swagger docs
- clean: dọn dẹp build artifacts
- help: liệt kê tất cả targets

2. Cấu trúc thư mục Go chuẩn

Cấu trúc đầy đủ theo Clean Architecture

my-go-project/
├── cmd/
│   ├── api/
│   │   └── main.go              # Entry point cho API server
│   ├── worker/
│   │   └── main.go              # Entry point cho background worker
│   └── migrate/
│       └── main.go              # Entry point cho migration tool
├── internal/
│   ├── config/
│   │   └── config.go            # Load cấu hình từ env/file
│   ├── handler/
│   │   ├── user_handler.go      # HTTP handler cho user
│   │   ├── product_handler.go   # HTTP handler cho product
│   │   └── health_handler.go    # Health check endpoint
│   ├── middleware/
│   │   ├── auth.go              # JWT authentication
│   │   ├── cors.go              # CORS config
│   │   ├── logger.go            # Request logging
│   │   ├── ratelimit.go         # Rate limiting
│   │   └── recovery.go          # Panic recovery
│   ├── model/
│   │   ├── user.go              # User entity
│   │   ├── product.go           # Product entity
│   │   └── pagination.go        # Pagination structs
│   ├── repository/
│   │   ├── user_repository.go   # User data access
│   │   ├── product_repository.go
│   │   └── repository.go        # Repository interface
│   ├── service/
│   │   ├── user_service.go      # Business logic cho user
│   │   ├── product_service.go
│   │   └── auth_service.go      # Authentication logic
│   ├── dto/
│   │   ├── user_dto.go          # Request/Response DTOs
│   │   └── product_dto.go
│   └── router/
│       └── router.go            # Route definitions
├── pkg/
│   ├── logger/
│   │   └── logger.go            # Shared logger package
│   ├── validator/
│   │   └── validator.go         # Custom validators
│   ├── response/
│   │   └── response.go          # Chuẩn hóa API response
│   ├── errors/
│   │   └── errors.go            # Custom error types
│   └── utils/
│       ├── hash.go              # Hashing utilities
│       └── token.go             # Token generation
├── migrations/
│   ├── 000001_create_users.up.sql
│   └── 000001_create_users.down.sql
├── docs/
│   ├── swagger.json
│   └── swagger.yaml
├── scripts/
│   ├── setup.sh
│   └── seed.sh
├── .air.toml                    # Hot reload config
├── .env.example
├── .gitignore
├── .golangci.yml                # Linter config
├── Dockerfile
├── docker-compose.yml
├── Makefile
├── go.mod
├── go.sum
└── README.md

Tạo cấu trúc bằng Claude

Tạo cấu trúc thư mục Go theo clean architecture cho dự án REST API quản lý sản phẩm:
- cmd/api/main.go: entry point
- internal/ với handler, service, repository, model, middleware, config, router, dto
- pkg/ với logger, validator, response, errors
- migrations/ cho database schema
- Mỗi file có boilerplate code cơ bản
- Interfaces cho repository và service layers

3. Phát triển API với Go

Thiết lập Gin Framework

Tạo Gin router setup trong internal/router/router.go:
- Router groups: /api/v1/public và /api/v1/protected
- Middleware chain: Logger -> Recovery -> CORS -> RateLimit
- Protected routes thêm JWT auth middleware
- Health check endpoint tại /health
- Swagger UI tại /swagger/*
- Graceful shutdown với signal handling

Router Groups và Versioning

Thiết lập API versioning với Gin:
- /api/v1/* cho version 1
- /api/v2/* cho version 2
- Public routes: login, register, health check
- Protected routes: CRUD operations cần JWT
- Admin routes: thêm role-based middleware
- Mỗi group dùng middleware riêng

Middleware Chain

Tạo middleware chain cho Gin:

1. Logger middleware: log request method, path, status, latency với zerolog
2. Recovery middleware: bắt panic, trả về 500 có format JSON
3. CORS middleware: config cho phép origin cụ thể, methods, headers
4. Rate limit middleware: 100 req/min per IP dùng golang.org/x/time/rate
5. Request ID middleware: thêm X-Request-ID header bằng UUID
6. Timeout middleware: cancel request sau 30s

Request/Response Models

Tạo hệ thống request/response chuẩn cho Go API:

1. Base response struct với fields: success, message, data, errors, meta
2. Pagination meta struct: page, per_page, total, total_pages
3. Error response struct: code, message, details
4. Request DTOs với validation tags (binding:"required")
5. Hàm helper: SuccessResponse(), ErrorResponse(), PaginatedResponse()
6. Custom validator cho email, phone Vietnam, CMND/CCCD

JSON Handling nâng cao

Tạo module xử lý JSON cho Go API:
- Custom JSON serializer với thời gian format "2006-01-02 15:04:05"
- Omitempty cho optional fields
- JSON tags với snake_case
- Custom Marshaler/Unmarshaler cho Money type (VND)
- Xử lý null fields với sql.NullString -> pointer types
- Enum type với custom JSON marshal (OrderStatus)

Ví dụ CRUD Handler đầy đủ

Tạo CRUD handler cho entity "Product" với Gin:
- GET /products — Danh sách có phân trang, filter, sort
- GET /products/:id — Chi tiết sản phẩm
- POST /products — Tạo mới (validate request body)
- PUT /products/:id — Cập nhật toàn bộ
- PATCH /products/:id — Cập nhật một phần
- DELETE /products/:id — Xóa mềm (soft delete)
- GET /products/:id/reviews — Danh sách review
- Handler gọi service layer, không chứa business logic
- Trả về response format chuẩn hóa
- Xử lý lỗi với custom error types

4. Database với Go

Kết nối PostgreSQL với GORM

Thiết lập kết nối PostgreSQL với GORM:
- Config từ biến môi trường (host, port, user, pass, dbname, sslmode)
- Connection pool: MaxIdleConns=10, MaxOpenConns=100, ConnMaxLifetime=1h
- Auto migrate khi development
- Logger cho SQL queries (chỉ khi debug mode)
- Hàm ping kiểm tra kết nối
- Graceful close khi shutdown
- Retry logic khi kết nối thất bại (3 lần, backoff 2s)

Kết nối với sqlx (lightweight)

Thiết lập PostgreSQL với sqlx thay vì ORM:
- Kết nối với pgx driver
- Named queries
- Struct scanning với db tags
- Transaction helper function
- Query builder đơn giản
- Connection pooling config
- Prepared statements cache

Migration Management

Thiết lập golang-migrate cho dự án:
- Cài đặt golang-migrate CLI
- Tạo migration: create_users_table
  + id UUID primary key
  + email unique not null
  + password_hash not null
  + full_name varchar(255)
  + role varchar(50) default 'user'
  + is_active boolean default true
  + created_at, updated_at timestamps
  + deleted_at nullable timestamp (soft delete)
  + Index trên email, created_at
- Makefile targets: migrate-create, migrate-up, migrate-down, migrate-force
- Tích hợp vào cmd/migrate/main.go

Repository Pattern

Tạo repository pattern cho Go với GORM:

1. Base repository interface với Generic type:
   - FindByID(ctx, id) -> (T, error)
   - FindAll(ctx, filter) -> ([]T, int64, error)
   - Create(ctx, entity) -> error
   - Update(ctx, entity) -> error
   - Delete(ctx, id) -> error

2. User repository implementation:
   - FindByEmail(ctx, email)
   - FindActiveUsers(ctx, pagination)
   - UpdatePassword(ctx, userID, hashedPassword)

3. Sử dụng context.Context cho timeout và cancellation
4. Trả về custom errors (ErrNotFound, ErrDuplicate)
5. Hỗ trợ filter và sort động

Transaction Handling

Tạo transaction helper cho Go:
- Hàm WithTransaction(ctx, db, fn) chạy fn trong transaction
- Tự động rollback khi có error hoặc panic
- Commit khi thành công
- Hỗ trợ nested transactions với savepoints
- Ví dụ: tạo order với order_items trong cùng transaction
- Context timeout cho transaction (30s)

Connection Pooling và Optimization

Tối ưu database connection cho Go production:
- Connection pool config hợp lý theo workload
- Health check endpoint kiểm tra DB connection
- Metrics: active connections, idle connections, wait time
- Prepared statement cache
- Query timeout với context
- Read replica support (master cho write, replica cho read)
- Circuit breaker pattern cho DB calls

5. Authentication

JWT Authentication

Tạo hệ thống JWT authentication cho Go API:

1. Auth service:
   - Login(email, password) -> (accessToken, refreshToken, error)
   - RefreshToken(refreshToken) -> (newAccessToken, error)
   - Logout(userID) -> error (blacklist token)

2. JWT config:
   - Access token: RS256, expire 15 phút
   - Refresh token: RS256, expire 7 ngày
   - Claims: userID, email, role, exp, iat, jti

3. Token storage:
   - Refresh token lưu trong database
   - Blacklisted tokens lưu trong Redis (TTL = remaining expiry)

4. Password hashing với bcrypt (cost=12)
5. Rate limit login: 5 attempts / 15 phút per IP

Middleware Authentication

Tạo JWT auth middleware cho Gin:
- Extract token từ Authorization header (Bearer scheme)
- Validate token signature và expiration
- Parse claims và set vào gin.Context
- Kiểm tra token không bị blacklist (Redis check)
- Trả về 401 nếu token invalid/expired
- Trả về 403 nếu token bị blacklist
- Helper: GetCurrentUser(c *gin.Context) -> *model.User
- Optional auth middleware (không bắt buộc đăng nhập)

RBAC (Role-Based Access Control)

Tạo hệ thống RBAC cho Go API:

1. Roles: admin, manager, user, guest
2. Permissions: users:read, users:write, products:read, products:write, orders:*
3. Role-permission mapping trong database

4. Middleware:
   - RequireRole("admin", "manager") — kiểm tra role
   - RequirePermission("users:write") — kiểm tra permission
   - RequireOwnership() — chỉ owner mới được sửa/xóa

5. Database schema: roles, permissions, role_permissions, user_roles
6. Cache permissions trong Redis (TTL 5 phút)
7. Casbin integration cho policy phức tạp (tuỳ chọn)

OAuth2 và Social Login

Thêm OAuth2 social login cho Go API:
- Google OAuth2 login
- Facebook OAuth2 login
- Hàm chung HandleOAuthCallback xử lý cho tất cả providers
- Tạo hoặc liên kết tài khoản khi login lần đầu
- Lưu provider info trong bảng user_social_accounts
- Trả về JWT tokens sau khi OAuth thành công

6. Testing Go

Unit Tests (Table-Driven Tests)

Viết unit tests cho user_service.go theo phong cách table-driven:
- Test CreateUser: thành công, email trùng, validation fail, db error
- Test GetUserByID: thành công, không tìm thấy, invalid ID
- Test UpdateUser: thành công, không tìm thấy, email đã tồn tại
- Test DeleteUser: thành công, không tìm thấy
- Mỗi test case có: name, input, mock setup, expected output, expected error
- Dùng testify/assert và testify/require
- Mock repository layer bằng interface

Mock với testify/mock

Tạo mock cho repository và external services:
- MockUserRepository implements UserRepository interface
- MockEmailService implements EmailService interface
- MockPaymentGateway implements PaymentGateway interface
- Sử dụng testify/mock
- Setup expectations: On("Method").Return(result, nil)
- Assert expectations: AssertExpectations(t)
- Ví dụ test service layer với mocked repository

Mock với gomock

Tạo mocks bằng gomock cho dự án:
- Cài đặt mockgen
- Generate mock từ interface: mockgen -source=repository.go -destination=mock_repository.go
- Makefile target: make mock
- Viết test với gomock controller
- ctrl := gomock.NewController(t)
- mock := NewMockUserRepository(ctrl)
- mock.EXPECT().FindByID(gomock.Any(), id).Return(user, nil)

Integration Tests

Viết integration tests cho Go API:
- Setup test database (PostgreSQL container với testcontainers-go)
- Migrate schema trước khi test
- Seed test data
- Test HTTP endpoints bằng httptest
- Test full flow: Register -> Login -> Create Resource -> Get Resource
- Cleanup sau mỗi test (truncate tables)
- Build tags: //go:build integration
- Chạy riêng: go test -tags=integration ./...

Benchmark Tests

Viết benchmark tests cho Go:
- Benchmark hàm hash password
- Benchmark JSON marshal/unmarshal
- Benchmark database query (với test DB)
- Benchmark concurrent map access
- Sử dụng b.ResetTimer(), b.ReportAllocs()
- Sub-benchmarks cho các input size khác nhau
- So sánh kết quả với benchstat
- Chạy: go test -bench=. -benchmem ./...

Test Coverage

Thiết lập test coverage cho dự án Go:
- go test -coverprofile=coverage.out ./...
- go tool cover -html=coverage.out -o coverage.html
- go tool cover -func=coverage.out (hiển thị % từng hàm)
- Makefile target: make test-cover
- Minimum coverage threshold: 80%
- Script kiểm tra coverage và fail nếu dưới threshold
- Tích hợp với CI/CD pipeline

Test Helpers

Tạo test helper package cho dự án Go:
- testutil.SetupTestDB() -> *gorm.DB (dùng SQLite in-memory cho unit test)
- testutil.SetupTestServer() -> *httptest.Server
- testutil.CreateTestUser(db) -> *model.User
- testutil.GenerateTestJWT(userID, role) -> string
- testutil.AssertJSON(t, expected, actual)
- testutil.LoadFixture(name) -> []byte
- Fixtures folder với sample JSON data

7. Concurrency Patterns

Goroutines và Channels

Tạo ví dụ minh hoạ concurrency patterns trong Go:

1. Fan-out/Fan-in: gửi email hàng loạt
   - 1 producer đọc từ database
   - N workers gửi email song song
   - 1 collector gom kết quả

2. Pipeline: xử lý ảnh
   - Stage 1: đọc file
   - Stage 2: resize
   - Stage 3: compress
   - Stage 4: upload S3
   - Mỗi stage là 1 goroutine, kết nối bằng channels

3. Semaphore: giới hạn concurrent API calls
   - Buffered channel làm semaphore
   - Tối đa 10 goroutines đồng thời

Worker Pool Pattern

Tạo worker pool pattern cho Go:
- Struct WorkerPool với: numWorkers, jobQueue, resultQueue, wg
- Method: Start(), Submit(job), Results() <-chan Result, Shutdown()
- Generic implementation với Go generics
- Ví dụ: xử lý 10,000 records với 50 workers
- Error handling: collect errors không dừng pool
- Graceful shutdown: đợi jobs đang chạy hoàn thành
- Metrics: jobs processed, errors, average duration

Context Cancellation

Tạo ví dụ context patterns trong Go:

1. Timeout context cho HTTP handler:
   - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
   - Pass context xuống service -> repository -> DB query
   - Trả về 504 nếu timeout

2. Cancellation propagation:
   - Parent context cancel -> tất cả child contexts cancel
   - Ví dụ: user cancel request -> dừng DB query + API call

3. Context values (cẩn thận khi dùng):
   - Lưu request ID, user info trong context
   - Helper functions: GetRequestID(ctx), GetUserFromContext(ctx)

4. Ví dụ thực tế: gọi 3 external APIs song song
   - Cancel tất cả nếu 1 API fail
   - Timeout tổng: 10s
   - Timeout từng API: 5s

Graceful Shutdown

Tạo graceful shutdown cho Go HTTP server:

1. Bắt signals: SIGINT, SIGTERM
2. Khi nhận signal:
   - Log "shutting down..."
   - Dừng nhận request mới
   - Đợi requests đang xử lý hoàn thành (timeout 30s)
   - Đóng database connections
   - Đóng Redis connections
   - Flush log buffer
   - Dừng background workers
   - Log "shutdown complete"

3. Force kill nếu quá timeout
4. Health check endpoint trả về 503 khi đang shutdown

Sync Patterns

Tạo ví dụ sync patterns trong Go:

1. sync.Mutex: thread-safe in-memory cache
2. sync.RWMutex: read-heavy cache (nhiều reader, ít writer)
3. sync.Once: singleton database connection
4. sync.WaitGroup: đợi nhiều goroutines hoàn thành
5. sync.Pool: object pooling cho JSON encoder
6. sync.Map: concurrent map khi keys ổn định
7. atomic operations: counter không cần mutex
8. errgroup: chạy song song với error handling

8. Go-specific Claude Prompts

Viết Go idiomatic

Refactor code Go này theo phong cách idiomatic Go:
- Tuân thủ Effective Go guidelines
- Error handling: không dùng panic, wrap errors với fmt.Errorf("%w", err)
- Naming: MixedCaps, viết tắt ALL CAPS (HTTP, URL, ID)
- Interfaces: nhỏ, 1-2 methods, đặt tên -er suffix (Reader, Writer)
- Receiver: dùng pointer receiver nếu mutate hoặc struct lớn
- Comments: bắt đầu bằng tên function/type
- Không dùng else sau if-return
- Early return pattern

Error Handling Patterns

Tạo error handling system cho Go API:

1. Custom error types:
   - AppError struct: Code, Message, HTTPStatus, Details
   - ErrNotFound, ErrUnauthorized, ErrForbidden, ErrValidation, ErrInternal
   - Implement error interface

2. Error wrapping:
   - Wrap errors với context: fmt.Errorf("get user %d: %w", id, err)
   - errors.Is() để check error type
   - errors.As() để extract error details

3. Error middleware:
   - Catch AppError -> trả về JSON format
   - Catch unknown errors -> log + trả về 500
   - Log stack trace cho internal errors

4. Sentinel errors cho package-level errors

Interface Design

Thiết kế interfaces cho Go project theo best practices:

1. Nguyên tắc:
   - "Accept interfaces, return structs"
   - Interface nhỏ, cụ thể (1-3 methods)
   - Định nghĩa interface phía consumer, không phía producer
   - Compose interfaces từ các interfaces nhỏ

2. Ví dụ cho e-commerce:
   - UserReader, UserWriter, UserRepository (combines cả hai)
   - OrderCreator, OrderFinder, OrderUpdater
   - PaymentProcessor interface cho multiple gateways
   - Notifier interface cho email, SMS, push notification

3. Testing:
   - Mọi dependency là interface -> dễ mock
   - Constructor nhận interfaces, không concrete types

Package Organization

Tổ chức packages cho Go project lớn:

1. Nguyên tắc:
   - Tránh circular dependencies
   - Package name ngắn, không underscore, không mixedCaps
   - internal/ cho code không export
   - pkg/ cho code có thể dùng lại

2. Dependency direction:
   - handler -> service -> repository
   - Không bao giờ ngược lại
   - Shared types trong model/ package

3. Tránh:
   - Package "utils", "helpers", "common" quá chung
   - God package chứa mọi thứ
   - Re-export từ package khác

4. Wire (dependency injection):
   - google/wire cho compile-time DI
   - Hoặc manual DI trong main.go

Tối ưu Performance

Tối ưu performance cho Go API:
- Profiling với pprof (CPU, memory, goroutine)
- Expose /debug/pprof endpoint (chỉ internal network)
- go tool pprof phân tích flame graph
- Giảm allocations: sync.Pool, pre-allocate slices
- String builder thay vì concatenation
- Tránh reflect khi có thể
- JSON: dùng jsoniter hoặc sonic thay encoding/json
- Connection pooling cho HTTP client và DB

9. Build và Deploy

Build Binary

# Build cho Linux
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o bin/app cmd/api/main.go

# Build với version info
go build -ldflags="-s -w -X main.version=1.2.3 -X main.buildTime=$(date -u +%Y%m%d%H%M%S)" -o bin/app cmd/api/main.go

# Build cho nhiều platforms
GOOS=linux GOARCH=amd64 go build -o bin/app-linux-amd64 cmd/api/main.go
GOOS=darwin GOARCH=arm64 go build -o bin/app-darwin-arm64 cmd/api/main.go
GOOS=windows GOARCH=amd64 go build -o bin/app-windows-amd64.exe cmd/api/main.go

Multi-stage Docker Build

Tạo Dockerfile multi-stage cho Go API:

Stage 1 (builder):
- Base image: golang:1.22-alpine
- Copy go.mod, go.sum -> go mod download (cache layer)
- Copy source code
- CGO_ENABLED=0 go build với ldflags "-s -w"

Stage 2 (runtime):
- Base image: alpine:3.19 (hoặc scratch cho minimal)
- Cài ca-certificates, tzdata
- Copy binary từ builder
- Non-root user
- EXPOSE port
- HEALTHCHECK instruction
- Entrypoint chạy binary

Thêm .dockerignore loại bỏ: .git, vendor, bin, *.test, docs

Docker Compose cho Development

Tạo docker-compose.yml cho Go development:

Services:
1. app: Go API với hot reload (air)
   - Volume mount source code
   - Depends on: db, redis
   - Environment từ .env

2. db: PostgreSQL 16
   - Volume cho persistent data
   - Init script tạo database

3. redis: Redis 7
   - Volume cho persistent data

4. migrate: golang-migrate
   - Chạy migrations khi khởi động

5. swagger-ui: Swagger UI
   - Mount docs/swagger.json

Networks và volumes config

Cross Compilation

Tạo script build cross-platform cho Go:
- Linux amd64 và arm64
- macOS amd64 và arm64 (Apple Silicon)
- Windows amd64
- Tên file format: app-{os}-{arch}
- Nén bằng tar.gz (Linux/macOS) hoặc zip (Windows)
- Tạo checksums SHA256
- Makefile target: make release VERSION=1.2.3

CI/CD Pipeline

Tạo GitHub Actions workflow cho Go project:

Jobs:
1. lint: chạy golangci-lint
2. test: chạy tests với coverage
   - Services: postgres, redis
   - Upload coverage lên Codecov
3. build: build binary và Docker image
4. security: chạy gosec và govulncheck
5. deploy:
   - Staging: auto deploy khi push main
   - Production: deploy khi tạo tag v*

Cache: go mod cache và go build cache
Matrix: Go 1.21, 1.22

Kubernetes Deployment

Tạo Kubernetes manifests cho Go API:
- Deployment: 3 replicas, resource limits, liveness/readiness probes
- Service: ClusterIP
- Ingress: nginx ingress với TLS
- ConfigMap: app config
- Secret: database credentials
- HPA: auto-scale 3-10 pods dựa trên CPU 70%
- PDB: minAvailable 2

10. Các prompt mẫu cho Go

Prompt 1: Khởi tạo dự án từ đầu

Tạo Go REST API cho hệ thống quản lý thư viện sách:
- Gin framework, PostgreSQL, GORM, Redis
- Entities: Book, Author, Category, User, BorrowRecord
- Clean architecture: handler -> service -> repository
- JWT authentication
- RBAC: admin (quản lý), librarian (thủ thư), member (độc giả)
- Pagination, filtering, sorting cho list endpoints
- Swagger documentation
- Docker Compose cho development
- Makefile đầy đủ

Prompt 2: Thêm tính năng mới

Thêm tính năng tìm kiếm full-text cho sách:
- Sử dụng PostgreSQL tsvector/tsquery
- Tìm kiếm theo tiêu đề, tác giả, mô tả
- Hỗ trợ tiếng Việt (unaccent extension)
- Ranking kết quả theo relevance
- Cache kết quả tìm kiếm phổ biến trong Redis (TTL 5 phút)
- Endpoint: GET /api/v1/books/search?q=keyword&page=1&limit=20

Prompt 3: Tối ưu Performance

Tối ưu performance cho API endpoints:
- Thêm Redis caching cho GET endpoints (cache-aside pattern)
- Cache invalidation khi data thay đổi
- Database query optimization: thêm indexes, preload associations
- Response compression với gzip middleware
- ETags cho conditional requests
- Benchmark trước và sau tối ưu

Prompt 4: WebSocket Real-time

Thêm WebSocket support cho Go API:
- Sử dụng gorilla/websocket
- Real-time notifications cho user
- Chat room feature
- Connection manager: track active connections
- Broadcast message tới room
- Ping/Pong heartbeat
- Reconnection handling phía client
- Scale với Redis PubSub (nhiều server instances)

Prompt 5: Background Job Processing

Tạo background job system cho Go:
- Sử dụng asynq (Redis-based)
- Job types: SendEmail, ProcessImage, GenerateReport
- Priority queues: critical, default, low
- Retry policy: 3 lần với exponential backoff
- Dead letter queue cho failed jobs
- Dashboard monitoring
- Graceful shutdown: đợi jobs đang chạy
- Scheduled jobs (cron): daily report, weekly cleanup

Prompt 6: Microservices Communication

Tạo gRPC service cho Go microservices:
- Proto file definitions cho UserService, OrderService
- gRPC server implementation
- gRPC client với connection pooling
- gRPC gateway (REST -> gRPC proxy)
- Interceptors: logging, auth, recovery
- Health checking protocol
- TLS mutual authentication
- Service discovery với Consul hoặc etcd

Prompt 7: File Upload và Processing

Tạo hệ thống upload file cho Go API:
- Upload ảnh: validate type (jpg, png, webp), max 10MB
- Resize ảnh thành nhiều kích thước (thumbnail, medium, large)
- Upload lên S3/MinIO
- Generate signed URL cho private files
- Streaming upload cho file lớn
- Progress tracking
- Virus scan với ClamAV
- Cleanup orphaned files (background job)

Prompt 8: Event-Driven Architecture

Tạo event system cho Go application:
- Event bus interface: Publish(event), Subscribe(eventType, handler)
- In-memory implementation cho development
- Kafka/NATS implementation cho production
- Events: UserCreated, OrderPlaced, PaymentCompleted
- Event sourcing cho Order aggregate
- Saga pattern cho distributed transaction: Order -> Payment -> Inventory
- Dead letter topic cho failed events
- Idempotency: xử lý duplicate events

Prompt 9: Monitoring và Observability

Thêm observability cho Go API:
- Structured logging với zerolog: request_id, user_id, duration
- Prometheus metrics:
  + http_requests_total (counter)
  + http_request_duration_seconds (histogram)
  + active_connections (gauge)
  + db_query_duration (histogram)
- OpenTelemetry tracing: distributed tracing qua services
- Health check endpoint: DB, Redis, external services
- Expose /metrics cho Prometheus scrape
- Grafana dashboard template

Prompt 10: Security Hardening

Tăng cường bảo mật cho Go API:
- Input validation và sanitization cho mọi endpoints
- SQL injection prevention (parameterized queries)
- XSS prevention trong response
- CSRF protection
- Security headers: HSTS, X-Content-Type-Options, X-Frame-Options
- Rate limiting per user và per IP
- Request body size limit
- Sensitive data masking trong logs
- gosec scan integration
- Dependency vulnerability check với govulncheck

Prompt 11: CLI Tool với Cobra

Tạo CLI tool bằng Go với Cobra:
- Root command: mytool
- Sub-commands: serve, migrate, seed, generate, version
- serve: khởi động API server, flags --port, --env
- migrate: up, down, create, status
- seed: chạy database seeder
- generate: tạo handler/service/repository từ template
- Persistent flags: --config, --verbose
- Viper integration đọc config file
- Auto-completion cho bash/zsh

Prompt 12: API Gateway Pattern

Tạo API Gateway đơn giản bằng Go:
- Reverse proxy tới các microservices
- Route matching dựa trên path prefix
- Load balancing: round-robin
- Rate limiting per client API key
- Request/Response transformation
- Circuit breaker cho backend services
- Centralized authentication
- Request logging và metrics
- Config hot-reload không cần restart

Mẹo sử dụng Claude Code với Go

Kiểm tra và fix lỗi nhanh

# Chạy linter và nhờ Claude fix
golangci-lint run ./... 2>&1 | head -50
claude "Fix tất cả linting errors này"
# Chạy test và nhờ Claude fix failures
go test ./... 2>&1
claude "Fix các test failures này"

Generate code từ spec

Đọc file docs/api-spec.yaml và generate:
- Handlers cho tất cả endpoints
- Request/Response DTOs
- Router setup
- Validation rules
- Unit tests cho mỗi handler

Refactor code hiện tại

Refactor package internal/handler:
- Tách handler lớn thành nhiều files nhỏ
- Extract common logic vào helper functions
- Thêm error handling nhất quán
- Thêm request validation
- Giữ nguyên tất cả test cases pass

Debug production issues

Phân tích pprof output này và gợi ý cách fix:
[paste pprof output]

Tập trung vào:
- Memory leaks (goroutine leaks)
- CPU hotspots
- Excessive allocations