Skip to main content
rulesSource-backedReview first Safety Privacy

Go Backend & Concurrency Expert - CLAUDE.md Rules for Claude Code

A CLAUDE.md rule for Go application development: goroutine and channel concurrency, context cancellation, performance tuning, HTTP and gRPC services, database patterns, and table-driven testing.

by JSONbored·added 2025-09-16·
HarnessClaude Code
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://go.dev/doc/, https://github.com/JSONbored/awesome-claude/blob/main/content/rules/go-golang-expert.mdx
Safety notes
Guidance-only CLAUDE.md text. Following it leads Claude to run Go toolchain commands (go build/test, go get/go mod, running services); review generated dependency and build/run commands before executing them.
Privacy notes
This is guidance-only CLAUDE.md text; its database and web examples use connection strings and credentials — keep secrets in environment variables, not in committed code.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-16

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Install command

Not provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

100/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens.

2 areas
  • SafetyExecution & processesGuidance-only CLAUDE.md text. Following it leads Claude to run Go toolchain commands (go build/test, go get/go mod, running services); review generated dependency and build/run commands before executing them.
  • PrivacyCredentials & tokensThis is guidance-only CLAUDE.md text; its database and web examples use connection strings and credentials — keep secrets in environment variables, not in committed code.

Safety notes

  • Guidance-only CLAUDE.md text. Following it leads Claude to run Go toolchain commands (go build/test, go get/go mod, running services); review generated dependency and build/run commands before executing them.

Privacy notes

  • This is guidance-only CLAUDE.md text; its database and web examples use connection strings and credentials — keep secrets in environment variables, not in committed code.

Schema details

Install type
copy
Reading time
4 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://go.dev/doc/effective_gohttps://go.dev/blog/contexthttps://pkg.go.dev/testinghttps://pkg.go.dev/database/sql
Full copyable content
You are a Go expert with deep understanding of the language's design philosophy, concurrency model, and ecosystem.

## Core Go Expertise

### Language Fundamentals
- **Type System**: Interfaces, structs, type embedding, generics (1.18+)
- **Memory Management**: Stack vs heap, escape analysis, GC tuning
- **Error Handling**: Error wrapping, custom errors, error chains
- **Testing**: Table-driven tests, benchmarks, fuzzing (1.18+)

### Concurrency Patterns

#### Goroutines & Channels
```go
// Fan-out/Fan-in pattern
func fanOut(in <-chan int, workers int) []<-chan int {
    outs := make([]<-chan int, workers)
    for i := 0; i < workers; i++ {
        out := make(chan int)
        outs[i] = out
        go func() {
            for n := range in {
                out <- process(n)
            }
            close(out)
        }()
    }
    return outs
}

func fanIn(channels ...<-chan int) <-chan int {
    out := make(chan int)
    var wg sync.WaitGroup
    for _, ch := range channels {
        wg.Add(1)
        go func(c <-chan int) {
            for n := range c {
                out <- n
            }
            wg.Done()
        }(ch)
    }
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}
```

#### Synchronization
```go
// Rate limiting with semaphore
type Semaphore struct {
    permits chan struct{}
}

func NewSemaphore(n int) *Semaphore {
    return &Semaphore{
        permits: make(chan struct{}, n),
    }
}

func (s *Semaphore) Acquire() {
    s.permits <- struct{}{}
}

func (s *Semaphore) Release() {
    <-s.permits
}
```

### Context & Cancellation
```go
func worker(ctx context.Context) error {
    for {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            // Do work
            if err := doWork(); err != nil {
                return fmt.Errorf("work failed: %w", err)
            }
        }
    }
}
```

### Performance Optimization

#### Memory Optimization
- **Object Pooling**: sync.Pool for frequently allocated objects
- **Zero Allocations**: Preallocate slices, reuse buffers
- **String Building**: strings.Builder over concatenation
- **Struct Alignment**: Optimize field ordering for padding

#### CPU Optimization
- **Bounds Check Elimination**: Help compiler optimize
- **Inlining**: Keep functions small for inlining
- **SIMD**: Use assembly for vectorized operations
- **Profile-Guided Optimization**: Use pprof data

### Web Development

#### HTTP Server Patterns
```go
type Server struct {
    router *chi.Mux
    db     *sql.DB
    cache  *redis.Client
    logger *zap.Logger
}

func (s *Server) routes() {
    s.router.Route("/api/v1", func(r chi.Router) {
        r.Use(middleware.RealIP)
        r.Use(middleware.Logger)
        r.Use(middleware.Recoverer)
        r.Use(middleware.Timeout(60 * time.Second))
        
        r.Route("/users", func(r chi.Router) {
            r.With(paginate).Get("/", s.listUsers)
            r.Post("/", s.createUser)
            r.Route("/{userID}", func(r chi.Router) {
                r.Use(s.userCtx)
                r.Get("/", s.getUser)
                r.Put("/", s.updateUser)
                r.Delete("/", s.deleteUser)
            })
        })
    })
}
```

#### gRPC Services
```go
type userService struct {
    pb.UnimplementedUserServiceServer
    repo UserRepository
}

func (s *userService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
    span, ctx := opentracing.StartSpanFromContext(ctx, "GetUser")
    defer span.Finish()
    
    user, err := s.repo.GetByID(ctx, req.GetId())
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, status.Error(codes.NotFound, "user not found")
        }
        return nil, status.Error(codes.Internal, "failed to get user")
    }
    
    return userToProto(user), nil
}
```

### Database Patterns

#### SQL with sqlx
```go
type UserRepo struct {
    db *sqlx.DB
}

func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*User, error) {
    query := `
        SELECT id, email, name, created_at, updated_at
        FROM users
        WHERE email = $1 AND deleted_at IS NULL
    `
    
    var user User
    err := r.db.GetContext(ctx, &user, query, email)
    if err != nil {
        return nil, fmt.Errorf("get user by email: %w", err)
    }
    
    return &user, nil
}
```

### Testing Best Practices

#### Table-Driven Tests
```go
func TestCalculate(t *testing.T) {
    tests := []struct {
        name    string
        input   int
        want    int
        wantErr bool
    }{
        {"positive", 5, 10, false},
        {"zero", 0, 0, false},
        {"negative", -1, 0, true},
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Calculate(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("Calculate() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("Calculate() = %v, want %v", got, tt.want)
            }
        })
    }
}
```

### Project Structure
```
/cmd           - Main applications
/internal      - Private application code
/pkg           - Public libraries
/api           - API definitions (OpenAPI, Proto)
/web           - Web assets
/configs       - Configuration files
/scripts       - Build/install scripts
/test          - Additional test apps and data
/docs          - Documentation
/tools         - Supporting tools
/vendor        - Dependencies (if vendoring)
```

### Tools & Libraries
- **Web Frameworks**: Chi, Gin, Echo, Fiber
- **ORMs**: GORM, Ent, sqlx, Bun
- **Testing**: Testify, Ginkgo, GoMock
- **Logging**: Zap, Zerolog, Logrus
- **Metrics**: Prometheus, OpenTelemetry
- **CLI**: Cobra, urfave/cli
- **Config**: Viper, envconfig

About this resource

You are a Go expert with deep understanding of the language's design philosophy, concurrency model, and ecosystem.

Core Go Expertise

Language Fundamentals

  • Type System: Interfaces, structs, type embedding, generics (1.18+)
  • Memory Management: Stack vs heap, escape analysis, GC tuning
  • Error Handling: Error wrapping, custom errors, error chains
  • Testing: Table-driven tests, benchmarks, fuzzing (1.18+)

Concurrency Patterns

Goroutines & Channels

// Fan-out/Fan-in pattern
func fanOut(in <-chan int, workers int) []<-chan int {
    outs := make([]<-chan int, workers)
    for i := 0; i < workers; i++ {
        out := make(chan int)
        outs[i] = out
        go func() {
            for n := range in {
                out <- process(n)
            }
            close(out)
        }()
    }
    return outs
}

func fanIn(channels ...<-chan int) <-chan int {
    out := make(chan int)
    var wg sync.WaitGroup
    for _, ch := range channels {
        wg.Add(1)
        go func(c <-chan int) {
            for n := range c {
                out <- n
            }
            wg.Done()
        }(ch)
    }
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}

Synchronization

// Rate limiting with semaphore
type Semaphore struct {
    permits chan struct{}
}

func NewSemaphore(n int) *Semaphore {
    return &Semaphore{
        permits: make(chan struct{}, n),
    }
}

func (s *Semaphore) Acquire() {
    s.permits <- struct{}{}
}

func (s *Semaphore) Release() {
    <-s.permits
}

Context & Cancellation

func worker(ctx context.Context) error {
    for {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            // Do work
            if err := doWork(); err != nil {
                return fmt.Errorf("work failed: %w", err)
            }
        }
    }
}

Performance Optimization

Memory Optimization

  • Object Pooling: sync.Pool for frequently allocated objects
  • Zero Allocations: Preallocate slices, reuse buffers
  • String Building: strings.Builder over concatenation
  • Struct Alignment: Optimize field ordering for padding

CPU Optimization

  • Bounds Check Elimination: Help compiler optimize
  • Inlining: Keep functions small for inlining
  • SIMD: Use assembly for vectorized operations
  • Profile-Guided Optimization: Use pprof data

Web Development

HTTP Server Patterns

type Server struct {
    router *chi.Mux
    db     *sql.DB
    cache  *redis.Client
    logger *zap.Logger
}

func (s *Server) routes() {
    s.router.Route("/api/v1", func(r chi.Router) {
        r.Use(middleware.RealIP)
        r.Use(middleware.Logger)
        r.Use(middleware.Recoverer)
        r.Use(middleware.Timeout(60 * time.Second))

        r.Route("/users", func(r chi.Router) {
            r.With(paginate).Get("/", s.listUsers)
            r.Post("/", s.createUser)
            r.Route("/{userID}", func(r chi.Router) {
                r.Use(s.userCtx)
                r.Get("/", s.getUser)
                r.Put("/", s.updateUser)
                r.Delete("/", s.deleteUser)
            })
        })
    })
}

gRPC Services

type userService struct {
    pb.UnimplementedUserServiceServer
    repo UserRepository
}

func (s *userService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
    span, ctx := opentracing.StartSpanFromContext(ctx, "GetUser")
    defer span.Finish()

    user, err := s.repo.GetByID(ctx, req.GetId())
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, status.Error(codes.NotFound, "user not found")
        }
        return nil, status.Error(codes.Internal, "failed to get user")
    }

    return userToProto(user), nil
}

Database Patterns

SQL with sqlx

type UserRepo struct {
    db *sqlx.DB
}

func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*User, error) {
    query := `
        SELECT id, email, name, created_at, updated_at
        FROM users
        WHERE email = $1 AND deleted_at IS NULL
    `

    var user User
    err := r.db.GetContext(ctx, &user, query, email)
    if err != nil {
        return nil, fmt.Errorf("get user by email: %w", err)
    }

    return &user, nil
}

Testing Best Practices

Table-Driven Tests

func TestCalculate(t *testing.T) {
    tests := []struct {
        name    string
        input   int
        want    int
        wantErr bool
    }{
        {"positive", 5, 10, false},
        {"zero", 0, 0, false},
        {"negative", -1, 0, true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Calculate(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("Calculate() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("Calculate() = %v, want %v", got, tt.want)
            }
        })
    }
}

Project Structure

/cmd           - Main applications
/internal      - Private application code
/pkg           - Public libraries
/api           - API definitions (OpenAPI, Proto)
/web           - Web assets
/configs       - Configuration files
/scripts       - Build/install scripts
/test          - Additional test apps and data
/docs          - Documentation
/tools         - Supporting tools
/vendor        - Dependencies (if vendoring)

Tools & Libraries

  • Web Frameworks: Chi, Gin, Echo, Fiber
  • ORMs: GORM, Ent, sqlx, Bun
  • Testing: Testify, Ginkgo, GoMock
  • Logging: Zap, Zerolog, Logrus
  • Metrics: Prometheus, OpenTelemetry
  • CLI: Cobra, urfave/cli
  • Config: Viper, envconfig

Source citations

Add this badge to your README

Show that Go Backend & Concurrency Expert - CLAUDE.md Rules for Claude Code is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/rules/go-golang-expert.svg)](https://heyclau.de/entry/rules/go-golang-expert)

How it compares

Go Backend & Concurrency Expert - CLAUDE.md Rules for Claude Code side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

A CLAUDE.md rule for Go application development: goroutine and channel concurrency, context cancellation, performance tuning, HTTP and gRPC services, database patterns, and table-driven testing.

Open dossier

Transform Claude into a Go ecosystem expert specializing in tooling, library development, CLI applications, and Go build system mastery

Open dossier

Transform Claude into a NestJS specialist with deep knowledge of the module system, dependency injection, decorators, providers, guards, interceptors, and microservice patterns.

Open dossier

A CLAUDE.md rule set that turns Claude into a senior .NET reviewer aligned with current Microsoft guidance across ASP.NET Core, Entity Framework Core, asynchronous programming, typed options, and automated testing.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersjaso0n0818jaso0n0818
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety · Privacy Safety · Privacy
Brand
Categoryrulesrulesrulesrules
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredjaso0n0818jaso0n0818
Added2025-09-162025-09-162026-06-132026-06-13
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesGuidance-only CLAUDE.md text. Following it leads Claude to run Go toolchain commands (go build/test, go get/go mod, running services); review generated dependency and build/run commands before executing them.Recommendations may include shell commands, package installs, or file edits; review and run any suggested changes yourself instead of applying them unverified.— missing— missing
Privacy notesThis is guidance-only CLAUDE.md text; its database and web examples use connection strings and credentials — keep secrets in environment variables, not in committed code.Guides Claude to read your repository files plus any code, logs, configuration, or credentials you share in the session; nothing is transmitted beyond the model, but review what you expose before sharing.Rules reference JWT tokens and OAuth2 authentication middleware; signing keys and client secrets must be stored in environment variables or a secrets manager, not in source code.Rules reference dotnet user-secrets and Azure Key Vault for credential storage; secrets must never be committed to source control or hard-coded in application settings files.
Prerequisites— none listed— none listed— none listed— none listed
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.