The complete 2026 AI prompt library for Go developers. REST APIs, microservices, concurrency, PostgreSQL, JWT, Redis, Docker, Kubernetes, testing, and debugging — with real prompts optimized for GPT-5.5, Claude Opus 4, Gemini 3.5 Flash, GitHub Copilot, and Cursor AI.
Go (Golang) is the language of production infrastructure in 2026. It runs Kubernetes, Docker, Cloudflare, Uber, and hundreds of the highest-throughput services on the internet. Its combination of static typing, first-class concurrency with goroutines, a minimal standard library, and compile-time safety makes it uniquely well-suited for microservices, CLI tools, cloud infrastructure, and high-performance backends.
Getting excellent Go code from AI requires more precision than most other languages. Go has strong idiomatic conventions — error handling patterns, context propagation, interface-driven design, table-driven testing — and AI models that don't know your preferences will often produce functional but un-idiomatic code that senior engineers would reject at code review.
This guide gives you production-ready prompt templates optimized specifically for GPT-5.5, Claude Opus 4, Gemini 3.5 Flash, GitHub Copilot, and Cursor AI, covering every major Go development pattern used in production systems.
What Are AI Prompts for Golang Developers?
An AI coding prompt is a structured instruction that tells a large language model (LLM) exactly what code to generate, using what patterns, with what constraints. For Go developers specifically, a well-crafted prompt specifies:
- Go version (1.22+ for range-over-int, 1.21+ for slog, 1.18+ for generics)
- The specific libraries (Chi vs Gin, sqlc vs GORM, go-redis vs rueidis)
- Idiomatic patterns (error wrapping with %w, context as first argument, interface-driven design)
- Testing requirements (table-driven, testify, mockery-generated mocks)
- Architecture constraints (clean architecture layers, dependency injection, interface boundaries)
Without this specificity, AI models produce code that compiles but violates Go idioms — inconsistent error handling, goroutines without cancellation, global state, or missing context propagation. The prompts in this guide produce code that passes code review at senior Go engineer level.
Why AI Prompt Engineering Matters in Modern Software Development
In a 2026 developer survey, engineers using structured AI prompts reported finishing features in 40–60% less time compared to engineers using informal, conversational AI requests. The difference is not which AI model you use — it is how precisely you instruct it.
For Go specifically, the precision gap is larger than most languages because:
- Go has no "one way to do it" for many patterns. Error handling, dependency injection, and config management all have multiple valid approaches. Without specifying which approach, AI will guess — and produce inconsistent codebases.
- Go's concurrency model is uniquely complex. Goroutines, channels, mutexes, and the context package interact in ways that require explicit instruction to get right. AI-generated goroutines without proper cancellation are a common source of production memory leaks.
- Go's type system rewards specificity. Specifying your interface signatures, struct tags, and generic constraints upfront produces code that integrates into your existing types correctly the first time.
The CRISP framework — Context, Role, Instructions, Specifics, Purpose — is particularly effective for coding prompts because it forces you to specify all five of these variables before the AI generates a single line of code.
How GPT-5.5, Claude Opus 4, and Gemini 3.5 Flash Generate Go Code
Not all AI models handle Go code equally. Here is a practical comparison of the three leading models for Go development in 2026:
| Capability | GPT-5.5 (OpenAI) | Claude Opus 4 (Anthropic) | Gemini 3.5 Flash (Google) |
|---|---|---|---|
| Multi-file project scaffolding | ★★★★★ | ★★★★ | ★★★★ |
| Goroutine & concurrency patterns | ★★★★★ | ★★★★★ | ★★★★ |
| Code review and refactoring | ★★★★ | ★★★★★ | ★★★★ |
| Idiomatic Go style adherence | ★★★★★ | ★★★★★ | ★★★★ |
| Test generation (table-driven) | ★★★★★ | ★★★★★ | ★★★★ |
| Structured output (JSON, gRPC proto) | ★★★★★ | ★★★★ | ★★★★ |
| Long codebase context | ★★★★ | ★★★★★ | ★★★★★ |
| Debugging and error explanation | ★★★★ | ★★★★★ | ★★★★ |
| Real-time docs & library versions | ★★★ | ★★★ | ★★★★★ |
| API cost efficiency | ★★★ | ★★★ | ★★★★★ |
Practical recommendation: Use GPT-5.5 for scaffolding new services and structured output. Use Claude Opus 4 for code review, architecture critique, and long codebase analysis. Use Gemini 3.5 Flash for checking current library versions, reading live Go documentation, and any task requiring access to real-time information. Use GitHub Copilot and Cursor AI inside your editor for day-to-day in-context code completion.
Best ChatGPT GPT-5.5 Prompts for Golang
GPT-5.5 is the top choice for scaffolding complete Go services. Its instruction-following accuracy and structured output reliability make it ideal for generating multi-file project structures, middleware chains, and JSON-formatted configuration files.
Microservice Scaffold Prompt (GPT-5.5)
You are a senior Go engineer (8+ years) who has built microservices handling 100K+ requests per second.
Design a production-ready Go microservice for a task management API:
Stack:
- Go 1.22
- HTTP: Chi router v5 (github.com/go-chi/chi/v5)
- Database: PostgreSQL with sqlc (type-safe SQL) + pgx v5 driver
- Cache: Redis with go-redis/v9
- Auth: JWT middleware (golang-jwt/jwt/v5) using RS256
- Config: environment variables via os.Getenv with a validated Config struct
- Logging: structured JSON with Go 1.21 standard library slog
- Observability: OpenTelemetry trace spans + Prometheus counters and histograms
Deliver:
1. Full directory structure: cmd/api/, internal/{handler,service,repository,model,middleware,config}/, pkg/{errors,response}/
2. main.go: dependency wiring, graceful shutdown on SIGTERM/SIGINT with 30-second timeout
3. Config struct with required field validation and documented defaults
4. Middleware stack order: requestID → structured logger → recovery → CORS → auth → rate-limiter
5. GET /health endpoint returning JSON: {"status":"ok","version":"...","db":"ok","redis":"ok"}
Idiomatic requirements:
- All service methods: func(ctx context.Context, ...) (T, error)
- Error types: define NotFoundError, ValidationError, UnauthorizedError in pkg/errors
- No global state except slog default logger
- Interfaces for all external dependencies (DB, cache, event publisher)
Output: all files, complete and compilable. Use Go module path: github.com/promptprepare/task-service
Worker Pool Prompt (GPT-5.5)
You are a Go concurrency expert.
Implement a generic, production-grade worker pool in Go 1.22 with generics.
Requirements:
- Pool[T any] struct: configurable number of workers (N), buffered job channel (capacity C)
- func NewPool[T any](ctx context.Context, workers int, capacity int, handler func(context.Context, T) error) *Pool[T]
- func (p *Pool[T]) Submit(job T) error — non-blocking, returns ErrPoolFull if buffer is full
- func (p *Pool[T]) Wait() — blocks until all submitted jobs are processed
- func (p *Pool[T]) Shutdown() — graceful: stop accepting new jobs, drain remaining, call Wait()
- Each worker: for-select loop with ctx.Done() for cancellation and job channel
- Error handling: failed jobs sent to error channel, accessible via p.Errors() <-chan error
- Metrics: atomic counters for processed/failed/pending jobs, exposed via p.Stats() PoolStats
Output: pool.go, pool_test.go (table-driven tests: happy path, pool full, context cancellation, panic recovery in worker)
Claude Opus 4 Prompt Examples for Go Developers
Claude Opus 4 (Anthropic) excels at Go code review, architecture analysis, and explaining complex concurrency patterns. Its long context window makes it the best choice for analyzing entire codebases and producing thorough technical documentation.
Code Review Prompt (Claude Opus 4)
I am a senior Go engineer preparing this code for production deployment at scale.
I need an honest, thorough code review that will pass the standards of a principal engineer at Google or Cloudflare.
Review criteria (assess each explicitly):
1. Idiomatic Go: naming conventions, error handling, context usage, interface design
2. Concurrency safety: data races, goroutine leaks, improper channel usage, missing cancellation
3. Security: input validation, SQL injection risk, JWT validation, secrets in logs
4. Performance: unnecessary allocations, blocking operations in hot paths, missing connection pooling
5. Testability: hard dependencies, missing interfaces, untestable global state
6. Error handling: naked errors, missing wrapping, log-then-return anti-pattern
7. Production readiness: graceful shutdown, health checks, structured logging, missing metrics
For each issue found:
- Severity: Critical / Major / Minor / Style
- Line reference
- What is wrong and why it matters in production
- Corrected code snippet
Be direct. Do not soften feedback. I need to know every problem before this ships.
[PASTE YOUR GO CODE HERE]
Architecture Critique Prompt (Claude Opus 4)
I am building a Go microservices platform for a B2B SaaS product expected to reach 50 million API requests per day within 18 months.
Current architecture:
- 6 Go microservices communicating via REST over HTTP
- PostgreSQL per service (separate databases)
- Redis for session storage only
- No message queue — services call each other synchronously
- Deployed on Kubernetes (GKE), 3 replicas per service
Please give me a critical architectural assessment:
1. What are the top 3 risks with this architecture at 50M requests/day?
2. Which synchronous service-to-service calls should become async events and why?
3. Should I add Kafka, NATS, or a different message broker? Explain the trade-offs for my scale.
4. Where would I add Redis beyond session storage?
5. Is my database-per-service approach correct, or should any services share a database?
For each recommendation: explain the problem it solves, the trade-off it introduces, and how to migrate incrementally without downtime.
Gemini 3.5 Flash Prompt Workflows for Go Developers
Gemini 3.5 Flash's real-time web access makes it uniquely valuable for Go development tasks that require current information: checking the latest library versions, reading live Go documentation, researching recently published CVEs in dependencies, and comparing current library options.
Dependency Research Prompt (Gemini 3.5 Flash)
I am starting a new Go 1.22 microservice project and need to choose the right libraries.
Search the web for the current state of each library category as of May 2026.
For each category, tell me:
- The recommended library in 2026 (not 2024 recommendations)
- Current version and release date
- Any recent breaking changes or deprecations
- Whether the original maintainer is still active
Categories to research:
1. HTTP router (Chi vs Gin vs Echo vs stdlib — what do senior Go engineers choose in 2026?)
2. SQL: sqlc vs GORM vs bun vs ent — current community consensus
3. Redis client: go-redis/v9 vs rueidis — performance difference and migration story
4. Config: viper vs envconfig vs godotenv — which is recommended for 12-factor apps?
5. Structured logging: slog (stdlib) vs zerolog vs zap — is slog now the standard?
6. JWT: golang-jwt/jwt/v5 — is there a newer maintained fork?
7. OpenTelemetry Go SDK — current stable version and any recent API changes?
Present as a decision matrix. I will implement this next week, so recency matters.
GitHub Copilot Prompting Techniques for Golang
GitHub Copilot operates differently from chat-based AI. It completes code inline based on the surrounding file context — your comments, function signatures, and existing code are the "prompt." Here are the techniques that produce the best Go code from Copilot:
- Write the function signature first, then the comment above it. Copilot reads both and produces a more accurate implementation than a comment alone.
- Define your interfaces before implementing them. Copilot will match the interface signature exactly when it can see the interface definition in the same file or package.
- Write the test file header first. Include the import list and the first table test struct. Copilot generates the remaining cases with remarkable accuracy when it sees the pattern.
- Use inline comments as micro-prompts:
// TODO: validate that deadline is not in the past, return ValidationErrorproduces far better code than a bare blank line.
Copilot Comment Patterns That Work Best
// CreateTask creates a new task in the repository.
// It validates that: title is non-empty (3-255 chars), deadline is in the future,
// assigneeID is a valid user in the same organization.
// On success: publishes TaskCreated event to event bus, returns created task.
// On validation failure: returns ValidationError with field-level messages.
// On DB conflict: returns DuplicateTaskError.
func (s *taskService) CreateTask(ctx context.Context, input CreateTaskInput) (*Task, error) {
// Copilot will complete from here with full implementation
}
Cursor AI Workflows for Golang Projects
Cursor AI is the most powerful AI coding environment for Go in 2026 because it maintains full project context across all your files simultaneously. Unlike paste-and-ask workflows with ChatGPT or Claude, Cursor reads your entire codebase — your interfaces, error types, middleware chain, and test patterns — before generating new code.
Best Cursor AI Workflows for Go
- @codebase + "implement X following the same pattern as Y": Point Cursor at an existing handler and ask it to implement a new handler following the exact same pattern. The output integrates with your error types, middleware, and response helpers automatically.
- Multi-file feature with Composer: Open Cursor Composer (Cmd+I / Ctrl+I), describe the feature end-to-end, and Cursor creates all necessary files: handler, service, repository, model, test, and migration. For Go, always add: "use the same middleware chain and error handling patterns as the existing handlers."
- Codebase Q&A for debugging: "@codebase why would this function return a nil pointer dereference?" — Cursor traces the call chain through your actual code, not a hypothetical example.
Cursor Composer Prompt for New Go Feature
@codebase Implement the full Comment feature for the Task entity:
Follow all existing patterns exactly:
- Same clean architecture layers: handler → service → repository
- Same error types from pkg/errors (NotFoundError, ValidationError, UnauthorizedError)
- Same context propagation pattern (ctx as first argument everywhere)
- Same table-driven test structure as task_service_test.go
- Same JSON response helper from pkg/response
New endpoints:
POST /api/v1/tasks/{taskId}/comments — CreateComment
GET /api/v1/tasks/{taskId}/comments — ListComments (cursor-based pagination)
DELETE /api/v1/comments/{commentId} — DeleteComment (author or admin only)
Database:
- Add comments table migration (id, task_id, user_id, content, created_at, deleted_at)
- Add sqlc queries following the same pattern as internal/repository/db/tasks.sql
Tests: table-driven, testify, mockery mocks, t.Parallel()
Do not change any existing files outside of registering the new route in routes.go.
AI Prompts for REST APIs in Go
Complete REST API Handler (Beginner)
You are a Go web developer.
Write a simple REST API for user management in Go using the Chi router:
- GET /users/{id} — get a single user by ID
- POST /users — create a new user
- PUT /users/{id} — update a user
- DELETE /users/{id} — delete a user
Use:
- Chi router v5
- Standard encoding/json for request/response
- In-memory map for storage (no database needed for this example)
- Proper HTTP status codes (200, 201, 400, 404, 500)
- JSON error responses: {"error": "message"}
Keep it simple, idiomatic Go. No external frameworks beyond Chi.
Production REST API with Validation (Intermediate)
You are a senior Go engineer.
Build a production-quality REST API handler for the Task resource:
- Chi router v5, Go 1.22
- Request body decoding: json.NewDecoder limited to 1MB with http.MaxBytesReader
- Validation: go-playground/validator/v10 with struct tags
- Custom error middleware: catches panics, maps domain errors to HTTP responses
- Response helpers: respondJSON(w, status, data), respondError(w, status, err)
- Context: extract authenticated user via UserFromContext(ctx)
Implement: CreateTask, GetTask, ListTasks (with filter query params), UpdateTask, DeleteTask
Error mapping:
- NotFoundError → 404
- ValidationError → 400 with field-level messages: {"errors":{"field":"message"}}
- UnauthorizedError → 403
- All other errors → 500 (log internally, return generic message to client)
Output: handler struct, all 5 methods, middleware, response helpers, and Chi router registration.
API Versioning and OpenAPI (Advanced)
You are a Go API architect.
Design a versioning strategy for a Go REST API that:
1. Supports simultaneous v1 and v2 endpoints (/api/v1/..., /api/v2/...)
2. Shares business logic (service layer) between versions
3. Has separate request/response structs per version (v1 uses JSON, v2 uses JSON with envelope)
4. Generates OpenAPI 3.1 spec automatically from code using swaggo/swag annotations
5. Maintains backward compatibility: adding fields to v1 responses is allowed, removing is not
Show:
- Chi router setup with version sub-routers
- Handler interface that both v1 and v2 implement
- Shared service call, different response transformation per version
- swaggo annotation example for one endpoint
- Deprecation header middleware for v1 endpoints: Deprecation: true, Sunset: 2027-01-01
AI Prompts for Microservices Architecture
gRPC Microservice (Advanced)
You are a Go gRPC expert building production microservices.
Build a gRPC service for task management:
Protobuf definition (task.proto):
- TaskService with RPCs: CreateTask, GetTask, ListTasks (server streaming), UpdateTask, DeleteTask
- Request/Response messages with proper field types and validation rules (protoc-gen-validate)
- Error details: use Google's error details (google.rpc.Status with ErrorInfo, FieldViolation)
Go gRPC server:
- Interceptor chain: logging (request/response duration), recovery (panics → codes.Internal), auth (JWT validation → codes.Unauthenticated), rate limiting
- Reflection service enabled (for grpcurl/Evans in development)
- Health check: grpc.health.v1 protocol implementation
- Graceful shutdown: GracefulStop() with timeout
Go gRPC client:
- Connection pool with keepalive parameters
- Client-side interceptors: retry (codes.Unavailable, codes.DeadlineExceeded — max 3 attempts, exponential backoff), timeout injection
- Circuit breaker: stop retrying after 5 consecutive failures
Output: proto file, server implementation, client helper, interceptors, and docker-compose for local development with both server and a test client.
AI Prompts for Goroutines and Concurrency
Concurrent Pipeline (Intermediate)
You are a Go concurrency expert.
Implement a concurrent data processing pipeline in Go 1.22:
Pipeline stages:
1. Producer: reads records from PostgreSQL (100K rows), sends to channel in batches of 100
2. Enricher: fan-out to 10 workers, each calls an external API to enrich each record (rate limited: 100 req/sec globally using golang.org/x/time/rate)
3. Transformer: applies business rules, filters invalid records
4. Sink: batches 500 records, bulk-inserts into PostgreSQL using pgx CopyFrom (fastest bulk insert)
Requirements:
- Context propagation: ctx.Done() respected at every stage
- Backpressure: each channel is buffered; stages block rather than drop data
- Error handling: first error cancels the entire pipeline via errgroup
- Progress reporting: emit progress events every 10 seconds (processed count, error count, estimated time remaining)
- Graceful shutdown: drain in-flight records before stopping
Show: all 4 stage functions, pipeline orchestrator, error group usage, and benchmark test.
Fan-Out Notification System (Intermediate)
You are a Go concurrency expert.
Implement a fan-out notification sender for a TaskAssigned event:
Requirements:
- Receive one TaskAssigned event
- Send 3 notifications concurrently: email (SendGrid), push notification (Firebase FCM), in-app (write to DB)
- Use errgroup.Group from golang.org/x/sync/errgroup
- Timeout: cancel all if any takes longer than 8 seconds (context.WithTimeout)
- Error semantics: if email fails, still send push and in-app (non-fatal per channel)
- Retry: each sender retries up to 2 times with 200ms, 400ms backoff before giving up
- Observability: record success/failure metric per channel (Prometheus counter)
Define interfaces for each sender so the implementation is testable.
Show the full NotificationService, all 3 sender implementations (minimal but real), tests with mocks.
AI Prompts for PostgreSQL and Database Optimization
sqlc Setup with Transactions (Intermediate)
You are a Go database expert using sqlc and pgx v5.
Set up a complete sqlc database layer for a task management service:
sqlc.yaml:
- engine: postgresql, Go 1.22, emit_json_tags: true, emit_db_tags: true
- null handling: sql_null_types (sql.NullString, sql.NullTime — not pointers)
- Output to internal/repository/db/
Schema (tasks table):
- id UUID DEFAULT gen_random_uuid()
- organization_id UUID NOT NULL (tenant isolation)
- title TEXT NOT NULL, description TEXT, status task_status (enum), priority task_priority (enum)
- due_date TIMESTAMPTZ, assigned_to UUID REFERENCES users(id)
- created_by UUID NOT NULL, created_at TIMESTAMPTZ DEFAULT now()
- updated_at TIMESTAMPTZ DEFAULT now(), deleted_at TIMESTAMPTZ (soft delete)
- Indexes: (organization_id, status, due_date), (organization_id, assigned_to), (deleted_at WHERE deleted_at IS NULL)
Queries:
- GetTaskByID: fetch single task (exclude deleted)
- ListTasksByOrg: filter by status/assignee/date range, cursor-based pagination (id > cursor), LIMIT
- CreateTask: INSERT RETURNING *
- UpdateTask: partial update using CASE WHEN for optional fields
- SoftDeleteTask: UPDATE SET deleted_at = now()
- CountByStatus: GROUP BY status for dashboard aggregate
Repository wrapper:
- ITaskRepository interface matching all query methods
- TaskRepository struct with *db.Queries + *pgxpool.Pool
- WithTx(ctx, fn func(*Queries) error) error — wraps operations in a transaction
- Health() error — pings DB, used by /health endpoint
Output: schema SQL, query SQL, sqlc.yaml, repository interface, and wrapper implementation.
AI Prompts for Docker and Kubernetes
Production Dockerfile (Intermediate)
You are a Go and Docker expert optimizing for production container images.
Write a production-optimized multi-stage Dockerfile for a Go microservice:
Builder stage:
- Base: golang:1.22-alpine
- Install: git, ca-certificates
- Set CGO_ENABLED=0, GOOS=linux, GOARCH=amd64
- Copy go.mod and go.sum first (cache dependency downloads)
- go mod download
- Copy source, go build -ldflags="-w -s -X main.version=${VERSION} -X main.commit=${COMMIT}" -o /app/server ./cmd/api/
Final stage:
- Base: gcr.io/distroless/static-debian12 (smallest, no shell, no package manager)
- COPY --from=builder /app/server /server
- COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
- Non-root USER: 65534 (nobody)
- EXPOSE 8080
- ENTRYPOINT ["/server"]
Also provide:
- .dockerignore file (exclude .git, *_test.go, docs/, *.md)
- docker-compose.yml: app + postgresql + redis with health checks and depends_on conditions
- Build script (build.sh) that injects VERSION and COMMIT as build args
Kubernetes Deployment (Advanced)
You are a Kubernetes expert deploying Go microservices on GKE.
Write complete Kubernetes manifests for a production Go microservice deployment:
Deployment:
- 3 replicas, rolling update: maxUnavailable 1, maxSurge 1
- Resource limits: 256Mi memory, 250m CPU; requests: 128Mi, 100m
- Liveness probe: HTTP GET /health, initialDelaySeconds 15, periodSeconds 10, failureThreshold 3
- Readiness probe: HTTP GET /ready, initialDelaySeconds 5, periodSeconds 5
- Environment: DB_URL from Secret, REDIS_URL from Secret, LOG_LEVEL from ConfigMap
- Security context: runAsNonRoot true, readOnlyRootFilesystem true, allowPrivilegeEscalation false
Service: ClusterIP, port 80 → targetPort 8080
HorizontalPodAutoscaler:
- Min 3, Max 10 replicas
- Scale up when CPU > 70% OR memory > 80%
- Scale-down stabilization: 300 seconds (prevent flapping)
PodDisruptionBudget: minAvailable 2
ConfigMap: log level, feature flags
Secret: DB credentials, Redis URL, JWT private key (base64 encoded)
Also provide: kustomize base structure for the above, with overlays for staging and production.
AI Prompts for Clean Architecture in Golang
You are a Go architect applying Clean Architecture (Uncle Bob) to a production service.
Design the complete Clean Architecture layer structure for a Go task management service:
Layer boundaries:
1. Domain layer (internal/domain/): Task, User, Organization entities. Business rules only.
No imports from other layers. No database types, no HTTP types.
2. Application layer (internal/application/): Use cases (CreateTask, AssignTask, CompleteTask).
Depends on domain + repository interfaces only. Orchestrates domain logic.
3. Infrastructure layer (internal/infrastructure/):
- repository/postgres: PostgreSQL implementations of domain repository interfaces
- repository/redis: Redis cache implementation
- messaging/kafka: Event publisher implementation
No business logic in this layer.
4. Interface layer (internal/interface/http): HTTP handlers, request/response DTOs, middleware.
Translates HTTP ↔ application layer. No business logic.
Dependency rule enforcement:
- Show how to use Go interfaces to invert dependencies across layers
- inner layers define interfaces; outer layers implement them
- The application layer never imports from infrastructure
- Show how main.go wires everything with dependency injection (no DI framework)
Provide:
- Directory structure for all 4 layers
- Domain entity example (Task with business methods: Assign, Complete, Reopen)
- Application use case example (CreateTaskUseCase)
- Repository interface in domain layer, PostgreSQL implementation in infrastructure
- main.go dependency wiring example showing the inversion of control
AI Prompts for CQRS and Event-Driven Systems
You are a Go architect building event-driven microservices with CQRS.
Implement CQRS (Command Query Responsibility Segregation) for the task management service:
Command side:
- Commands: CreateTaskCommand, AssignTaskCommand, CompleteTaskCommand, DeleteTaskCommand
- CommandBus: routes commands to handlers, middleware: validation → authorization → handler → event publishing
- Each CommandHandler produces domain events stored in the event store
- Outbox pattern: events written to outbox table in the same DB transaction as the command
- Outbox processor: polls outbox, publishes to Kafka, marks as published (at-least-once delivery)
Query side:
- Separate read models (denormalized, optimized for queries): TaskListView, TaskDetailView, TaskDashboardView
- Read model store: PostgreSQL read replicas (write model = normalized, read model = flat projections)
- Projector: subscribes to Kafka events, updates read models
- Queries go directly to read models, never to the write model
Event types: TaskCreated, TaskAssigned, TaskCompleted, TaskDeleted (all with correlation IDs for tracing)
Show:
- Command struct definitions and CommandBus interface
- One CommandHandler (CreateTaskCommandHandler) with full outbox pattern
- Kafka consumer group for projector
- Read model PostgreSQL schema vs write model schema
- Query handler reading from the read model
AI Prompts for Authentication and JWT Security
You are a Go security engineer building production authentication.
Implement complete JWT-based authentication for a Go Chi API:
JWT configuration:
- Algorithm: RS256 (asymmetric — private key signs, public key verifies)
- Claims: sub (user UUID), org (organization UUID), role (string), plan (string), iat, exp (1 hour), jti (unique ID for revocation)
- Key rotation: support multiple public keys identified by kid header field
Middleware (func(http.Handler) http.Handler):
- Extract token from Authorization: Bearer {token}
- Parse and validate: expiry, issuer ("https://auth.promptprepare.com"), audience (service name)
- Check JTI against Redis revocation set (revoke individual tokens on logout)
- Inject validated claims into context using typed context key (never plain string keys)
- On any error: return 401 JSON immediately, never call next
Context helpers:
- func UserIDFromContext(ctx) (uuid.UUID, bool)
- func OrganizationIDFromContext(ctx) (uuid.UUID, bool)
- func RequireRole(roles ...string) func(http.Handler) http.Handler — 403 if role not in list
- func RequirePlan(plans ...string) func(http.Handler) http.Handler — 403 with upgrade message
Security hardening:
- Rate limit failed auth attempts: 5 failures per IP per minute → 429
- Log suspicious patterns: repeated invalid tokens from same IP (structured slog, do not log token value)
- Never log or return the raw JWT token in error responses
Output: middleware, context helpers, Redis revocation check, and tests for expired/invalid/revoked tokens.
AI Prompts for Redis and Caching
You are a Go Redis expert building production caching strategies.
Implement a multi-layer caching system for a Go service using go-redis/v9:
Cache strategies to implement:
1. Read-through cache for task queries:
- Check Redis first (key: "task:{id}", TTL 5 minutes)
- On miss: fetch from PostgreSQL, populate cache, return
- On DB error: serve stale cache if available (resilient to DB outages)
2. Write-through cache on task updates:
- Write to DB first (primary source of truth)
- On DB success: update cache (SET with new TTL)
- On cache write failure: log warning, do NOT fail the request (cache is secondary)
3. Cache invalidation on task deletion:
- Delete from DB
- Delete cache key
- Publish cache invalidation event to Redis Pub/Sub (for multi-instance invalidation)
4. Rate limiting with sliding window (Redis sorted set):
- Key: "ratelimit:{userID}", score = timestamp, member = request UUID
- ZREMRANGEBYSCORE to remove old entries, ZCARD to count, ZADD to add current
- EXPIRE to clean up idle keys
- Return remaining requests and reset time for Retry-After header
5. Distributed lock for idempotent operations:
- SETNX with expiry (prevent double-processing)
- Lock: SET key value NX PX timeout
- Unlock: Lua script (check value before delete — prevents unlocking another process's lock)
Output: CacheService interface, Redis implementation, Lua unlock script, and tests using miniredis (no real Redis needed in tests).
AI Prompts for Unit Testing and Benchmarking
Table-Driven Tests (Intermediate)
You are a Go testing expert.
Write complete table-driven tests for the TaskService.CreateTask method.
[PASTE YOUR CreateTask IMPLEMENTATION HERE]
Test requirements:
tests := []struct {
name string
input CreateTaskInput
setupMocks func(repo *MockTaskRepository, events *MockEventPublisher, cache *MockCache)
wantErr bool
wantErrType interface{} // for errors.As check
wantTask *Task // nil if wantErr is true
}
Required test cases:
- "happy path: valid task created and event published"
- "validation: title is empty string"
- "validation: title exceeds 255 characters"
- "validation: due_date is in the past"
- "validation: assigned_to user not in organization"
- "repository: DB connection failure"
- "repository: duplicate title in project (unique constraint)"
- "events: publisher fails but task still created (eventual consistency)"
- "cache: write-through cache failure is non-fatal"
Each test:
- t.Parallel()
- Use testify/require for fatal assertions (stop test if nil pointer would panic)
- Use testify/assert for non-fatal assertions
- Verify mock expectations: repo.AssertExpectations(t), events.AssertExpectations(t)
- Assert exact error type with errors.As, not just non-nil
Output: full test file including mock generation directive (//go:generate mockery) and all test cases.
Benchmark Test (Advanced)
You are a Go performance engineer.
Write benchmark tests for a high-throughput Go HTTP handler that processes task creation requests:
func BenchmarkCreateTaskHandler(b *testing.B) — benchmarks the full HTTP handler stack
Benchmark scenarios:
- BenchmarkCreateTask_Simple: minimal valid request, no DB (mock returns immediately)
- BenchmarkCreateTask_WithValidation: full validation pass
- BenchmarkCreateTask_JSONEncoding: measure JSON encode/decode overhead specifically
- BenchmarkCreateTask_Concurrent: b.RunParallel() to simulate 100 concurrent requests
For each benchmark:
- b.ResetTimer() after setup
- b.ReportAllocs() to track allocations per operation
- Use httptest.NewRecorder and httptest.NewServer
- Realistic request body (not empty)
Also add:
- pprof setup in main_test.go: TestMain that enables CPU and memory profiling
- go test flags comment explaining: -bench=., -benchmem, -benchtime=10s, -cpuprofile=cpu.prof
- A short explanation of what the allocation numbers mean and how to reduce them
Target: handler should process < 500µs p99 at 1000 concurrent connections. Show where the bottlenecks would appear.
AI Prompts for Debugging Production Issues
You are a senior Go SRE with experience debugging production incidents.
I have a Go microservice experiencing this issue in production:
Symptom: Memory usage grows steadily from 150MB to 2GB over 48 hours, then the pod is OOM-killed.
The service handles ~5,000 HTTP requests per second.
Debugging approach:
1. What are the top 5 causes of memory leaks in Go HTTP services? List them in order of likelihood.
2. Show me how to add runtime/pprof endpoints to the running service (HTTP handler for /debug/pprof/) WITHOUT redeploying
3. How do I capture a heap profile from a running Kubernetes pod?
4. Show the exact pprof commands to: identify top allocating functions, find goroutine leaks, compare two heap profiles over time
5. What does it mean if the heap profile shows: large allocations in bufio.ReadWriter? In bytes.Buffer? In net/http transport?
6. Show me the 3 most common Go code patterns that cause this specific "slow leak" behavior (grows over hours, not immediately)
For each cause: show the problematic code pattern and the fix.
Picking the Right AI Model for Go Work
Go's simplicity and strong opinions work in AI's favor — there's usually one right way to do things. The biggest differentiator between models is whether they produce idiomatic Go (interfaces, error wrapping, goroutine safety) or "Go-shaped" code that compiles but fights the language.
| Model | Best For (Go) | Weak Spot | When to Reach For It |
|---|---|---|---|
| Claude Sonnet | Interface design, error handling patterns, context propagation, goroutine lifecycle management | Occasionally over-engineers simple Go patterns with unnecessary abstraction | Designing the service interface graph, reviewing goroutine leak risk, planning context cancellation flow |
| ChatGPT GPT-5.5 / GPT-5.5 | HTTP handler boilerplate, CRUD service generation, struct definitions | Generates global variables for dependencies instead of injection; misses race conditions in goroutine patterns | Generating Chi router handlers from an API spec, writing struct and interface boilerplate |
| Gemini 3.5 Flash | Go ecosystem research, library comparisons (pgx vs database/sql, Chi vs Gin vs Echo), current Go release notes | Less depth on goroutine synchronization patterns | Comparing Go 1.22+ features, researching the best library for a specific use case |
| Cursor | In-editor completion that respects your interface definitions and error types | Sometimes generates incorrect error wrapping (fmt.Errorf without %w) | Active Go development — especially valuable when it can see your interface definitions |
| GitHub Copilot | Completing repetitive Go patterns: table-driven tests, struct methods, middleware | Generates error returns without wrapping; misses context cancellation | Completing test cases in table-driven test format after seeing the pattern |
| Grok | Direct comparison: Go vs Rust for your use case, concurrency model trade-offs | Less precise on Go-specific standard library patterns | Getting a direct answer on whether Go or Rust is right for a specific performance requirement |
| DeepSeek | Algorithm implementations, data structure code, competitive-programming-style Go | Production patterns: missing graceful shutdown, missing context propagation | Implementing a specific algorithm or data structure in idiomatic Go |
Claude and Cursor are the strongest pairing for production Go. Claude for design and review; Cursor for implementation with your codebase context. ChatGPT is fine for greenfield boilerplate but misses race conditions and context patterns in complex concurrent code. Always verify goroutine-heavy code with the race detector (go test -race) regardless of which model generated it — no AI reliably catches all race conditions.
Where AI Goes Wrong in Go
- Global state for dependencies. AI frequently generates
var db *sql.DBas a package-level global instead of injecting it through function parameters or a struct. Global state makes testing painful and introduces race conditions. Always specify "inject all dependencies — no package-level globals." - Goroutine leaks from missing cancellation. AI generates
go func() { ... }()without passing a context.Context or providing a stop mechanism. Every goroutine that reads from a channel or runs indefinitely needs a way to stop. Specify "all goroutines must respect context cancellation and stop on context.Done()." - Error handling: missing %w wrapper. AI generates
fmt.Errorf("failed to do X: %s", err)instead offmt.Errorf("failed to do X: %w", err). The %w wrapper preserves the error chain for errors.Is() and errors.As() — without it, callers can't inspect the underlying error type. - Incorrect mutex usage. AI generates mutex locks without deferred unlock — a panic mid-function leaves the mutex locked forever. Always use
defer mu.Unlock()immediately aftermu.Lock(). - HTTP server without timeouts. AI generates
http.ListenAndServe(addr, handler)with no read/write timeouts. Without them, slow clients can hold goroutines indefinitely. Specify "set ReadTimeout, WriteTimeout, and IdleTimeout on http.Server."
Advanced Prompt Engineering for Go Developers
The following techniques consistently improve Go code output quality across all major AI models — GPT-5.5, Claude Opus 4, Gemini 3.5 Flash, and Grok 4.
The Go Specification Template
Always include this block at the start of any complex Go prompt:
Environment:
- Go 1.22
- Module: github.com/[your-org]/[your-service]
Existing packages (do not re-define these types):
- pkg/errors: NotFoundError, ValidationError, UnauthorizedError, ConflictError
- pkg/response: func respondJSON(w, status, data), func respondError(w, status, err)
- internal/middleware: requestIDMiddleware, loggerMiddleware, authMiddleware(jwtKey)
- internal/model: Task, User, Organization (show struct definitions if relevant)
Idiomatic requirements (non-negotiable):
- Errors wrapped with fmt.Errorf("%w", err) at every layer
- context.Context as first argument to all service and repository methods
- Interfaces for all external dependencies
- Table-driven tests with testify
- No named return values
- No global mutable state
Chain-of-Thought Debugging Prompt
Think step by step before writing any code.
First, analyze this Go function:
[PASTE FUNCTION]
Step 1: Identify all possible error paths (nil returns, panics, goroutine leaks)
Step 2: Identify any concurrency issues (data races, missing locks, improper channel use)
Step 3: Identify performance issues (unnecessary allocations, blocking calls)
Step 4: THEN write the corrected version with all issues resolved
Show your analysis before the corrected code.
Common AI Coding Prompt Mistakes for Go
| Mistake | What AI Generates | What You Actually Need |
|---|---|---|
| "Write error handling for my Go code" | Generic if err != nil { return err } everywhere | Specify: wrap with %w, define custom error types, log only at top handler layer, map to HTTP status codes in middleware |
| "Run these tasks concurrently" | go func() { ... }() without WaitGroup or cancellation | Specify: errgroup.Group, context.WithTimeout, ctx.Done() in every goroutine, defer wg.Done() |
| "Write tests for my service" | Individual test functions with hardcoded inputs | Specify: table-driven pattern, testify, mockery mocks, t.Parallel(), errors.As assertions |
| "Build a REST API in Go" | All logic in main.go, global DB variable | Specify: clean architecture layers, dependency injection in main.go, interface boundaries between layers |
| "Connect to PostgreSQL" | database/sql with no connection pool config | Specify: pgxpool.Pool, MaxConns, MinConns, HealthCheckPeriod, connection string from environment only |
| "Add logging to my service" | fmt.Println or log.Printf | Specify: slog with JSON handler, structured fields (slog.String("key","value")), request ID propagation via context |
Best Practices for AI-Assisted Go Development
- Always specify your Go version. Go 1.22 has range-over-int, Go 1.21 has slog, Go 1.18+ has generics. Specifying the version prevents AI from generating code that won't compile.
- Include your existing interface signatures. Paste your ITaskRepository or IEventPublisher interface. AI will implement it exactly — preventing type mismatch errors that cost 20 minutes to debug.
- Ask for tests alongside implementation. Add "Output: implementation AND table-driven tests with testify" to every prompt. Tests reveal assumptions the AI made that may be wrong for your use case.
- Specify the exact library, not the category. "Use go-redis/v9" not "use Redis". "Use golang-jwt/jwt/v5" not "use JWT". Specifying the library version prevents the AI from mixing API styles from different library versions.
- Define your error types upfront. If you have NotFoundError and ValidationError in your codebase, mention them. AI will use your types instead of inventing new ones that conflict with your existing error handling.
- Use multi-turn conversations for complex features. Generate the interface → review it → generate the implementation → review it → generate the tests. Each review step improves the next generation.
- Cross-validate with DeepSeek V4 for algorithm-heavy code. For graph algorithms, dynamic programming, or complex data structures, run the same prompt on both GPT-5.5 and DeepSeek V3. Compare outputs and take the better implementation.
The Future of AI Coding and Go Prompt Engineering
Go development is entering a new phase of AI integration in 2026. Here is what the next 18 months looks like for Go developers:
- Agentic code generation: Tools like Cursor AI's autonomous mode and OpenAI Codex agent can now implement entire GitHub issues end-to-end in Go — creating files, running tests, fixing errors, and committing code. The developer's role shifts from writing code to reviewing and guiding AI-generated implementations.
- AI-powered code review at scale: Teams at the frontier are running Claude Opus 4 on every pull request, catching security vulnerabilities, idiomatic violations, and performance regressions before human review. Go's strict type system and explicit error handling make it especially well-suited for AI code review accuracy.
- Prompt-driven TDD: Write the test prompt first — describe the behavior you want via test cases — then ask AI to generate the implementation that passes those tests. This "prompt-driven TDD" produces more accurate implementations because the AI optimizes for your specific test expectations.
- Multi-model Go workflows: The most productive Go teams in 2026 use a model portfolio: GPT-5.5 for scaffolding, Claude Opus 4 for review, Gemini 3.5 Flash for library research, GitHub Copilot for in-editor completion, and Grok 4 for competitive intelligence on open-source library choices.
- OpenAI o3 for complex algorithms: OpenAI o3's extended reasoning capability makes it the best choice for Go's hardest algorithmic problems — distributed system design, consensus algorithms, and performance-critical data structure implementations where multiple reasoning steps matter.
The skill that compounds most in this environment is not the ability to write Go — it is the ability to write precise prompts that specify idiomatic Go patterns, architecture constraints, and quality requirements clearly enough that AI gets it right the first time. PromptPrepare's CRISP framework guide covers the universal foundation. This article gives you the Go-specific vocabulary to apply it.
Final Thoughts
Go is one of the most AI-friendly languages because its strong conventions — explicit errors, context propagation, interface-driven design, and table-driven tests — are easy to specify in a prompt. When you tell an AI model exactly which patterns to follow, it produces code that passes code review at senior engineer level on the first attempt.
The biggest unlock is moving from informal AI conversations to structured prompts with an explicit Go specification block: version, existing types, idiomatic requirements, and test expectations. This shifts AI output from "mostly correct but needs significant editing" to "review, minor adjustments, commit."
Start with the microservice scaffold prompt from the GPT-5.5 section, run it through PromptPrepare to get a model-optimized version, and commit your first AI-scaffolded Go service today. The time savings compound with every feature you build afterward.
Before You Prompt: Go Context Setup
Go's strong idiomatic conventions — explicit error handling, context propagation, interface-based composition — are easy to specify and dramatically improve AI output quality. Without a context block, AI generates Go code that works but violates the conventions your team will flag in code review:
Context for all Go prompts in this session:
- Language: Go 1.22+ (use range over integers, slices.Contains, maps.Keys where applicable)
- HTTP router: Chi 5 for REST APIs (NOT Gin unless I specify)
- Database: sqlc with pgx v5 for PostgreSQL
Avoid GORM — prefer explicit SQL with type-safe generated code
- Error handling: errors.Is / errors.As, fmt.Errorf("context: %w", err)
Never: panic() for business logic, bare error string returns without wrapping
- Context: context.Context as FIRST parameter to every function that does I/O
Never embed context in structs
- Concurrency: errgroup.WithContext (golang.org/x/sync/errgroup) for concurrent operations
Never: raw goroutines without sync.WaitGroup or context cancellation
- Config: environment variables via github.com/kelseyhightower/envconfig
Never: init() for application startup, global package-level state
The context-as-first-parameter rule is the highest-impact Go idiom. It enables request cancellation, deadline propagation, and tracing to flow through the entire call stack. Functions that embed context in a struct (an anti-pattern the Go team explicitly discourages) break this propagation chain. This single constraint produces the biggest improvement in the quality of AI-generated Go code.
3 Common Mistakes When Prompting AI for Go
Mistake 1: Goroutines without context cancellation
Asking for "concurrent API calls in Go" produces goroutines launched with go func() { ... }() that run until completion with no cancellation mechanism. When the parent request times out or is cancelled, these goroutines keep running — consuming connections, database locks, and memory. Specify: "use errgroup.WithContext(ctx) for all concurrent operations — every goroutine must check ctx.Done() and clean up on cancellation." This one requirement prevents goroutine leaks that are invisible in testing and catastrophic under load.
Mistake 2: Global package-level variables for service instances
AI frequently generates var db *sql.DB and var redisClient *redis.Client as package-level globals initialized in init(). This pattern makes testing impossible (you can't inject a test database), breaks concurrent test isolation, and creates implicit coupling between packages. Specify: "use dependency injection — pass all services (database, cache, config) as constructor arguments, never package-level globals or init()." A Go service struct with injected dependencies is easy to test and reason about.
Mistake 3: Not wrapping errors with context
Asking to "add error handling" produces if err != nil { return err } patterns that propagate errors without adding context. When the error surfaces at the API layer, you see "sql: no rows in result set" with no indication of which query, which handler, or which user action caused it. Specify: "wrap all errors with fmt.Errorf including the operation context: fmt.Errorf("getUserByEmail %s: %w", email, err)." The resulting error chain includes the full call path and makes production debugging tractable.
Further Reading
Resources for AI-assisted Go development:
- How engineering teams use AI for Go development — AI strategies for Go microservices: from code generation to performance profiling with pprof
- How to write the perfect AI prompt — the CRISP framework applied to Go-specific patterns and idioms
- AI Coding Prompt Library — 50+ copy-ready prompts for Go REST APIs, concurrency, PostgreSQL with sqlc, and Go testing
Continue learning: How to Write the Perfect AI Prompt — ChatGPT vs Claude vs Gemini: Complete 2026 Guide — AI Prompt Templates Library
Help & Answers
Frequently Asked Questions
Found this helpful?
Save it to your library or share with your team.
Keep Reading