go-context — скилл для Claude Code: что делает и как установить
Задаёт правила работы с context.Context в Go: от сигнатур функций и таймаутов до разделения данных запроса и параметров.
npx skills add cxuu/golang-skills --skill go-context -a claude-codeЧто делает go-context
Скилл учит агента следовать идиоматичным практикам Go при работе с context.Context. Он требует передавать контекст первым параметром в функциях, запрещает сохранять его в полях структур и блокирует создание кастомных интерфейсов контекста. Для передачи данных задаётся строгая иерархия: обычные параметры стоят на первом месте, а context.Value остаётся только для идентификаторов запросов, трейсинга и авторизации.
Внутри скилла зафиксированы типовые паттерны отмены операций через select и <-ctx.Done(), обязательный вызов defer cancel() сразу после создания производного контекста, а также ссылки на references/PATTERNS.md для работы с HTTP-запросами. Скилл опирается на стандартную библиотеку Go начиная с версии 1.7.
Этот набор инструкций намеренно не управляет жизненным циклом горутин и примитивами синхронизации — такие задачи вынесены в смежный скилл go-concurrency. Ещё одно исключение касается структур: контекст допускается сохранять в типе только тогда, когда метод обязан совпадать со сторонним интерфейсом.
Какие задачи решает
- вынести
context.Contextпервым аргументом во всех функциях - убрать контекст из полей структур в сигнатуры методов
- организовать отмену долгих операций и настройку таймаутов
- разделить данные запроса и явные параметры вызова
Примеры запросов агенту
- Проверь методы структуры Worker и убери контекст из её полей
- Добавь отмену сетевого запроса через context.WithTimeout с вызовом defer cancel
- Помоги прокинуть request ID через context.Context в HTTP-хэндлере
Как установить go-context
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-context -a claude-code2Вручную: положить файлы
~/.claude/skills/go-context/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/go-context/
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-context -a codex2Вручную: положить файлы
.agents/skills/go-context/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-context -a cursor2Вручную: положить файлы
.cursor/skills/go-context/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install cxuu/golang-skills go-context2Вручную: положить файлы
.github/skills/go-context/SKILL.md1Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-context -a gemini-cli2Командой платформы
gemini skills install https://github.com/cxuu/golang-skills --path skills/go-contextВручную: положить файлы
.devin/skills/go-context/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add cxuu/golang-skills --skill go-context -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора19
Похожие
Вопросы о go-context
Как установить go-context в Claude Code?
Выполните команду npx skills add cxuu/golang-skills --skill go-context -a claude-code в терминале проекта.
Зачем нужен скилл go-context?
Он задаёт для ИИ стандарты работы с контекстом: передачу первым аргументом, корректный вызов cancel() и запрет на хранение контекста внутри структур.
Управляет ли go-context жизненным циклом горутин?
Нет, правила координации горутин и синхронизации вынесены автором в отдельный скилл go-concurrency.
Исходный текст
SKILL.md · Apache-2.0
---
name: go-context
description: Use when working with context.Context in Go — placement in signatures, propagating cancellation and deadlines, and storing values in context vs parameters. Also use when cancelling long-running operations, setting timeouts, or passing request-scoped data, even if they don't mention context.Context directly. Does not cover goroutine lifecycle or sync primitives (see go-concurrency).
---
# Go Context Usage
> Compatibility: `context` has been in the standard library since Go 1.7.
## Resource Routing
- `references/PATTERNS.md` - Read when deriving contexts, checking cancellation, handling HTTP request contexts, or using typed context-value keys.
## Context as First Parameter
Functions that use a Context should accept it as their **first parameter**:
```go
func F(ctx context.Context, /* other arguments */) error
func ProcessRequest(ctx context.Context, req *Request) (*Response, error)
```
This is a strong convention in Go that makes context flow visible and consistent
across codebases.
---
## Don't Store Context in Structs
Do not add a Context member to a struct type. Instead, pass `ctx` as a parameter
to each method that needs it:
```go
// Bad: Context stored in struct
type Worker struct {
ctx context.Context // Don't do this
}
// Good: Context passed to methods
type Worker struct{ /* ... */ }
func (w *Worker) Process(ctx context.Context) error {
// Context explicitly passed — lifetime clear
}
```
**Exception**: Methods whose signature must match an interface in the standard
library or a third-party library may need to work around this.
---
## Don't Create Custom Context Types
Do not create custom Context types or use interfaces other than `context.Context`
in function signatures:
```go
// Bad: Custom context type
type MyContext interface {
context.Context
GetUserID() string
}
// Good: Use standard context.Context with value extraction
func Process(ctx context.Context) error {
userID := GetUserID(ctx)
}
```
---
## Where to Put Application Data
Consider these options in order of preference:
1. **Function parameters** — most explicit and type-safe
2. **Receiver** — for data that belongs to the type
3. **Globals** — for truly global configuration (use sparingly)
4. **Context value** — only for request-scoped data
Context values are appropriate for:
- Request IDs and trace IDs
- Authentication/authorization info that flows with requests
- Deadlines and cancellation signals
Context values are **not** appropriate for:
- Optional function parameters
- Data that could be passed explicitly
- Configuration that doesn't vary per-request
---
## Common Patterns
### Deriving Contexts
Always `defer cancel()` immediately after creating a derived context:
```go
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
```
### Checking Cancellation
```go
select {
case <-ctx.Done():
return ctx.Err()
default:
// Do work
}
```
### Context Immutability
Contexts are immutable — it's safe to pass the same `ctx` to multiple
concurrent calls that share the same deadline and cancellation signal.
---
## Related Skills
- **Goroutine coordination**: See [go-concurrency](../go-concurrency/SKILL.md) when using context for goroutine cancellation, select-based timeouts, or errgroup
- **Error handling**: See [go-error-handling](../go-error-handling/SKILL.md) when deciding how to wrap or return `ctx.Err()` cancellation errors
- **Interface design**: See [go-interfaces](../go-interfaces/SKILL.md) when designing APIs that accept context alongside interfaces
- **Request-scoped logging**: See [go-logging](../go-logging/SKILL.md) when injecting loggers into context or adding request IDs to structured log output
© cxuu · Apache-2.0 · cxuu/golang-skills