golang-context

bởi samber

Cách sử dụng context.Context theo phong cách Go — truyền qua các ranh giới API, hủy bỏ, thời gian chờ và thời hạn, giá trị trong phạm vi yêu cầu, context.WithoutCancel cho công việc nền tồn tại lâu hơn yêu cầu. Áp dụng khi thiết kế truyền context qua các tầng, gỡ lỗi context bị rò rỉ hoặc chưa hết hạn, chọn giữa context.Background/TODO/WithoutCancel, hoặc lưu trữ giá trị trong context. Không dùng cho mã chỉ đơn thuần chấp nhận ctx làm tham số đầu tiên.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-context

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-context skill takes precedence.

Go context.Context Best Practices

context.Context is Go's mechanism for propagating cancellation signals, deadlines, and request-scoped values across API boundaries and between goroutines. Think of it as the "session" of a request — it ties together every operation that belongs to the same unit of work.

Best Practices Summary

  1. The same context MUST be propagated through the entire request lifecycle: HTTP handler → service → DB → external APIs
  2. ctx MUST be the first parameter, named ctx context.Context
  3. NEVER store context in a struct — pass explicitly through function parameters
  4. NEVER pass nil context — use context.TODO() if unsure
  5. cancel() MUST be called on all control-flow paths for WithCancel/WithTimeout/WithDeadline, unless ownership of the context and cancel function is explicitly returned or transferred
  6. context.Background() MUST only be used at the top level (main, init, tests)
  7. Use context.TODO() as a placeholder when you know a context is needed but don't have one yet
  8. NEVER create a new context.Background() in the middle of a request path
  9. Context value keys MUST be unexported types to prevent collisions
  10. Context values MUST only carry request-scoped metadata — NEVER function parameters
  11. Use context.WithoutCancel (Go 1.21+) when spawning background work that must outlive the parent request

Creating Contexts

SituationUse
Entry point (main, init, test)context.Background()
Function needs context but caller doesn't provide one yetcontext.TODO()
Inside an HTTP handlerr.Context()
Need cancellation controlcontext.WithCancel(parentCtx)
Need a deadline/timeoutcontext.WithTimeout(parentCtx, duration)

Context Propagation: The Core Principle

The most important rule: propagate the same context through the entire call chain. When you propagate correctly, cancelling the parent context cancels all downstream work automatically.

// ✗ Bad — creates a new context, breaking the chain
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(context.Background(), "INSERT INTO orders ...", order.ID)
}

// ✓ Good — propagates the caller's context
func (s *OrderService) Create(ctx context.Context, order Order) error {
    return s.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
}

Deep Dives

  • Cancellation, Timeouts & Deadlines — How cancellation propagates: WithCancel for manual cancellation, WithTimeout for automatic cancellation after a duration, WithDeadline for absolute time deadlines. Patterns for listening (<-ctx.Done()) in concurrent code, AfterFunc callbacks, and WithoutCancel for operations that must outlive their parent request (e.g., audit logs).

  • Context Values & Cross-Service Tracing — Safe context value patterns: unexported key types to prevent namespace collisions, when to use context values (request ID, user ID) vs function parameters. Trace context propagation: OpenTelemetry trace headers, correlation IDs for log aggregation, and marshaling/unmarshaling context across service boundaries.

  • Context in HTTP Servers & Service Calls — HTTP handler context: r.Context() for request-scoped cancellation, middleware integration, and propagating to services. HTTP client patterns: NewRequestWithContext, client timeouts, and retries with context awareness. Database operations: always use *Context variants (QueryContext, ExecContext) to respect deadlines.

Cross-References

  • → See the samber/cc-skills-golang@golang-concurrency skill for goroutine cancellation patterns using context
  • → See the samber/cc-skills-golang@golang-database skill for context-aware database operations (QueryContext, ExecContext)
  • → See the samber/cc-skills-golang@golang-observability skill for trace context propagation with OpenTelemetry
  • → See the samber/cc-skills-golang@golang-design-patterns skill for timeout and resilience patterns

Enforce with Linters

Many context pitfalls are caught automatically by linters: govet, staticcheck. → See the samber/cc-skills-golang@golang-lint skill for configuration and usage.

Thêm skills từ samber

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
Các mẫu thiết kế Golang theo phong cách bản địa — tùy chọn hàm, hàm khởi tạo, luồng lỗi và xếp tầng, quản lý tài nguyên và vòng đời, tắt máy an toàn, khả năng phục hồi, kiến trúc, tiêm phụ thuộc, xử lý dữ liệu, truyền phát, v.v. Áp dụng khi lựa chọn rõ ràng giữa các mẫu kiến trúc, triển khai tùy chọn hàm, thiết kế API hàm khởi tạo, thiết lập tắt máy an toàn, áp dụng các mẫu phục hồi, hoặc hỏi mẫu Go bản địa nào phù hợp với một vấn đề cụ thể.
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Các mẫu và phương pháp tối ưu hiệu năng Golang - nếu X là điểm nghẽn, thì áp dụng Y. Bao gồm giảm cấp phát, hiệu quả CPU, bố trí bộ nhớ, tinh chỉnh GC, pooling, caching, và tối ưu đường dẫn nóng. Sử dụng khi profiling hoặc benchmark đã xác định được điểm nghẽn và bạn cần mẫu tối ưu phù hợp để khắc phục. Cũng sử dụng khi thực hiện đánh giá mã hiệu năng để đề xuất cải tiến hoặc benchmark có thể giúp xác định các cải thiện hiệu năng nhanh chóng. Không dành cho phương pháp đo lường (→...
developmentcode-review
golang-security
samber
Các phương pháp bảo mật tốt nhất và phòng ngừa lỗ hổng cho Golang. Bao gồm injection (SQL, lệnh, XSS), mật mã học, an toàn hệ thống tệp, bảo mật mạng, cookie, quản lý bí mật, an toàn bộ nhớ và ghi nhật ký. Áp dụng khi viết, xem xét hoặc kiểm tra mã Go về bảo mật, hoặc khi làm việc trên bất kỳ mã rủi ro nào liên quan đến mật mã, I/O, quản lý bí mật, xử lý đầu vào người dùng hoặc xác thực. Bao gồm cấu hình các công cụ bảo mật.
securitycode-reviewdevelopment
golang-database
samber
Hướng dẫn toàn diện về truy cập cơ sở dữ liệu Go — truy vấn tham số hóa, quét struct, cột NULL, giao dịch, mức cô lập, SELECT FOR UPDATE, connection pool, xử lý hàng loạt, truyền context và công cụ migration. Sử dụng khi viết, xem xét hoặc gỡ lỗi mã Golang tương tác với PostgreSQL, MariaDB, MySQL hoặc SQLite; để kiểm thử cơ sở dữ liệu; hoặc cho các câu hỏi về database/sql, sqlx hoặc pgx. KHÔNG tạo lược đồ cơ sở dữ liệu hoặc SQL migration.
developmentdatabase
golang-lint
samber
Các phương pháp linting tốt nhất và cấu hình golangci-lint cho các dự án Golang — chạy linters, cấu hình .golangci.yml, loại bỏ cảnh báo bằng chỉ thị nolint, diễn giải đầu ra lint, và lựa chọn linters. Sử dụng khi cấu hình golangci-lint, hỏi về cảnh báo lint hoặc loại bỏ nolint, thiết lập công cụ chất lượng mã, hoặc chọn linters. Cũng sử dụng khi người dùng đề cập đến golangci-lint, go vet, staticcheck, hoặc revive.
developmentcode-reviewtesting