golang-patterns
Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.
About this skill
This skill provides an AI agent with deep knowledge of Go-specific design patterns and best practices. It covers critical areas such as the functional options pattern for flexible configuration, designing small and focused interfaces, implementing robust dependency injection, mastering Go's powerful concurrency patterns (goroutines, channels), effective error handling strategies, and organizing Go packages for maintainability and scalability. Leveraging this skill, AI agents can generate production-ready Go code that adheres to Go idioms, promoting readability, efficiency, and robustness. It's part of a comprehensive collection aimed at enhancing AI capabilities for various software development tasks, particularly for building robust API designs and enterprise-grade systems.
Best use case
Generating new Go code snippets or entire modules that follow best practices. Refactoring existing Go code to align with idiomatic Go patterns and improve design. Debugging or identifying anti-patterns and proposing better solutions in Go projects. Learning or demonstrating how to apply specific Go design principles effectively. Building scalable, maintainable, and robust Go applications, services, or APIs.
Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.
The AI agent will produce Go code that is: idiomatic and follows Go's conventions; well-structured, utilizing appropriate design patterns; robust, with effective error handling and concurrency management; maintainable and scalable, with clear package organization; and highly performant and efficient where applicable.
Practical example
Example input
Generate a Go service constructor using the functional options pattern. The service should manage user data, allowing configuration for a database connection string and a timeout duration. Provide an example usage demonstrating default and custom configurations.
Example output
```go
// Response generated using 'golang-patterns' skill
package main
import (
"fmt"
"time"
)
// UserService represents the service that manages user data.
type UserService struct {
dbConnStr string
timeout time.Duration
// Add other service dependencies here
}
// Option is a function type for configuring UserService.
type Option func(*UserService)
// WithDBConnection provides an option to set the database connection string.
func WithDBConnection(connStr string) Option {
return func(s *UserService) {
s.dbConnStr = connStr
}
}
// WithTimeout provides an option to set the service operation timeout.
func WithTimeout(timeout time.Duration) Option {
return func(s *UserService) {
s.timeout = timeout
}
}
// NewUserService creates a new UserService instance with optional configurations.
func NewUserService(opts ...Option) *UserService {
// Default configuration
service := &UserService{
dbConnStr: "mongodb://localhost:27017/users",
timeout: 5 * time.Second,
}
// Apply options
for _, opt := range opts {
opt(service)
}
return service
}
// Example method for UserService
func (s *UserService) GetUser(id string) (string, error) {
// Simulate database call
fmt.Printf("Fetching user %s with DB: %s and timeout: %s\n", id, s.dbConnStr, s.timeout)
time.Sleep(1 * time.Second) // Simulate work
return fmt.Sprintf("User-%s", id), nil
}
func main() {
// Example 1: Default service
defaultService := NewUserService()
fmt.Println("--- Default Service ---")
defaultService.GetUser("123")
// Example 2: Custom database connection
customDBService := NewUserService(
WithDBConnection("postgres://user:pass@host:port/dbname"),
)
fmt.Println("\n--- Custom DB Service ---")
customDBService.GetUser("456")
// Example 3: Custom timeout and database
fullConfigService := NewUserService(
WithTimeout(10*time.Second),
WithDBConnection("mysql://root:password@127.0.0.1:3306/users"),
)
fmt.Println("\n--- Full Config Service ---")
fullConfigService.GetUser("789")
}
```When to use this skill
- When developing new Go applications or features that require clean, maintainable, and idiomatic code.
- When improving the architecture or design of existing Go projects to enhance robustness and scalability.
- When seeking to understand or apply specific Go design patterns like functional options or proper error handling techniques.
- When reviewing Go code to ensure it follows best practices for concurrency, dependency management, and package organization.
When not to use this skill
- When working with programming languages other than Go.
- When the task involves basic syntax or trivial code generation that does not require the application of complex design patterns.
- When the primary goal is rapid prototyping where initial adherence to strict patterns might momentarily slow down development, though it is beneficial in the long run.
- When the AI agent is not configured or capable of leveraging external skills for code generation and pattern application.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/golang-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How golang-patterns Compares
| Feature / Agent | golang-patterns | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Go Patterns
> This skill provides comprehensive Go patterns extending common design principles with Go-specific idioms.
## Functional Options
Use the functional options pattern for flexible constructor configuration:
```go
type Option func(*Server)
func WithPort(port int) Option {
return func(s *Server) { s.port = port }
}
func NewServer(opts ...Option) *Server {
s := &Server{port: 8080}
for _, opt := range opts {
opt(s)
}
return s
}
```
**Benefits:**
- Backward compatible API evolution
- Optional parameters with defaults
- Self-documenting configuration
## Small Interfaces
Define interfaces where they are used, not where they are implemented.
**Principle:** Accept interfaces, return structs
```go
// Good: Small, focused interface defined at point of use
type UserStore interface {
GetUser(id string) (*User, error)
}
func ProcessUser(store UserStore, id string) error {
user, err := store.GetUser(id)
// ...
}
```
**Benefits:**
- Easier testing and mocking
- Loose coupling
- Clear dependencies
## Dependency Injection
Use constructor functions to inject dependencies:
```go
func NewUserService(repo UserRepository, logger Logger) *UserService {
return &UserService{
repo: repo,
logger: logger,
}
}
```
**Pattern:**
- Constructor functions (New* prefix)
- Explicit dependencies as parameters
- Return concrete types
- Validate dependencies in constructor
## Concurrency Patterns
### Worker Pool
```go
func workerPool(jobs <-chan Job, results chan<- Result, workers int) {
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
results <- processJob(job)
}
}()
}
wg.Wait()
close(results)
}
```
### Context Propagation
Always pass context as first parameter:
```go
func FetchUser(ctx context.Context, id string) (*User, error) {
// Check context cancellation
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// ... fetch logic
}
```
## Error Handling
### Error Wrapping
```go
if err != nil {
return fmt.Errorf("failed to fetch user %s: %w", id, err)
}
```
### Custom Errors
```go
type ValidationError struct {
Field string
Msg string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}
```
### Sentinel Errors
```go
var (
ErrNotFound = errors.New("not found")
ErrInvalid = errors.New("invalid input")
)
// Check with errors.Is
if errors.Is(err, ErrNotFound) {
// handle not found
}
```
## Package Organization
### Structure
```
project/
├── cmd/ # Main applications
│ └── server/
│ └── main.go
├── internal/ # Private application code
│ ├── domain/ # Business logic
│ ├── handler/ # HTTP handlers
│ └── repository/ # Data access
└── pkg/ # Public libraries
```
### Naming Conventions
- Package names: lowercase, single word
- Avoid stutter: `user.User` not `user.UserModel`
- Use `internal/` for private code
- Keep `main` package minimal
## Testing Patterns
### Table-Driven Tests
```go
func TestValidate(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid", "test@example.com", false},
{"invalid", "not-an-email", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := Validate(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("got error %v, wantErr %v", err, tt.wantErr)
}
})
}
}
```
### Test Helpers
```go
func testDB(t *testing.T) *sql.DB {
t.Helper()
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("failed to open test db: %v", err)
}
t.Cleanup(func() { db.Close() })
return db
}
```
## When to Use This Skill
- Designing Go APIs and packages
- Implementing concurrent systems
- Structuring Go projects
- Writing idiomatic Go code
- Refactoring Go codebasesRelated Skills
swiftui-patterns
SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。
perl-patterns
现代 Perl 5.36+ 的惯用法、最佳实践和约定,用于构建稳健、可维护的 Perl 应用程序。
kotlin-ktor-patterns
Ktor 服务器模式,包括路由 DSL、插件、身份验证、Koin DI、kotlinx.serialization、WebSockets 和 testApplication 测试。
kotlin-exposed-patterns
JetBrains Exposed ORM 模式,包括 DSL 查询、DAO 模式、事务、HikariCP 连接池、Flyway 迁移和仓库模式。
rust-patterns
Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.
laravel-patterns
Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.
springboot-patterns
Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.
jpa-patterns
JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.
django-patterns
Django architecture patterns, REST API design with DRF, ORM best practices, caching, signals, middleware, and production-grade Django apps.
python-patterns
Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Use when working with Python code to apply Pythonic patterns.
postgres-patterns
PostgreSQL database patterns for query optimization, schema design, indexing, and security. Quick reference for common patterns, index types, data types, and anti-pattern detection. Based on Supabase best practices.
golang-testing
Go testing best practices including table-driven tests, test helpers, benchmarking, race detection, coverage analysis, and integration testing patterns. Use when writing or improving Go tests.