Golang rules

From Luohaothu/everything-codex · View interactive version

Golang rules is an AI agent skill from the GitHub repository Luohaothu/everything-codex. Comprehensive Go coding rules covering style, patterns, testing, and security

How to use this skill

Skill file

Go Coding Rules

Coding Style

Immutability (CRITICAL)

ALWAYS create new objects, NEVER mutate existing ones:

// Pseudocode
WRONG:  modify(original, field, value) -> changes original in-place
CORRECT: update(original, field, value) -> returns new copy with change

Rationale: Immutable data prevents hidden side effects, makes debugging easier, and enables safe concurrency.

File Organization

MANY SMALL FILES > FEW LARGE FILES:

Formatting

Design Principles

Error Handling

ALWAYS handle errors comprehensively:

Always wrap errors with context:

if err != nil {
    return fmt.Errorf("failed to create user: %w", err)
}

Input Validation

ALWAYS validate at system boundaries:

Code Quality Checklist

Before marking work complete:

Patterns

Skeleton Projects

When implementing new functionality:

  1. Search for battle-tested skeleton projects
  2. Evaluate options for security, extensibility, relevance
  3. Clone best match as foundation
  4. Iterate within proven structure

Repository Pattern

Encapsulate data access behind a consistent interface:

API Response Format

Use a consistent envelope for all API responses:

Functional Options

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
}

Small Interfaces

Define interfaces where they are used, not where they are implemented.

Dependency Injection

Use constructor functions to inject dependencies:

func NewUserService(repo UserRepository, logger Logger) *UserService {
    return &UserService{repo: repo, logger: logger}
}

Testing

Minimum Test Coverage: 80%

Test Types (ALL required):

  1. Unit Tests - Individual functions, utilities, components
  2. Integration Tests - API endpoints, database operations
  3. E2E Tests - Critical user flows

Test-Driven Development

MANDATORY workflow:

  1. Write test first (RED)
  2. Run test - it should FAIL
  3. Write minimal implementation (GREEN)
  4. Run test - it should PASS
  5. Refactor (IMPROVE)
  6. Verify coverage (80%+)

Troubleshooting Test Failures

  1. Check test isolation
  2. Verify mocks are correct
  3. Fix implementation, not tests (unless tests are wrong)

Framework

Use the standard go test with table-driven tests.

Race Detection

Always run with the -race flag:

go test -race ./...

Coverage

go test -cover ./...

Security

Mandatory Security Checks

Before ANY commit:

Secret Management

apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
    log.Fatal("OPENAI_API_KEY not configured")
}

Security Scanning

```bash

gosec ./...

```

Context & Timeouts

Always use context.Context for timeout control:

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()

Security Response Protocol

If security issue found:

  1. STOP immediately
  2. Fix CRITICAL issues before continuing
  3. Rotate any exposed secrets
  4. Review entire codebase for similar issues
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.