---
name: go-resource-management
description: "Resource management in Go using defer, context, and proper lifecycle control."
language: go
---

# Go Resource Management

Best practices for managing memory, file handles, and goroutines in Go.

## Guidelines
- **Use `defer` for cleanup**: Immediately follow resource acquisition with a `defer` to release it (e.g., `f.Close()`, `resp.Body.Close()`).
- **Context for Cancellation**: Use `context.Context` to propagate cancellation and timeouts across goroutines and API calls.
- **Avoid Goroutine Leaks**: Every goroutine should have a way to exit, usually triggered by a context cancellation or a closed channel.
- **Close Channels from the Sender**: To avoid "send on closed channel" panics, let the sender handle channel closing.
- **Buffer Management**: Use `io.Copy` or `bufio` for efficient data transfer without loading everything into memory.
- **Connection Pooling**: Use built-in pooling in `database/sql` or `http.Client` instead of creating new connections for every request.

## Tools & Libraries
- **context (standard library)**: The fundamental tool for lifecycle management.
- **golangci-lint (goleak)**: Specifically identifies goroutine leaks in tests.
- **runtime**: For inspecting memory and goroutine stats at runtime.

## Trigger Scenarios
- When opening files, network connections, or database handles.
- When starting long-running goroutines.
- When implementing APIs that need timeouts.
- When a developer reports an "out of memory" or "too many open files" error.

<!-- synapsis-dsai-managed -->
