Go has become the lingua franca of cloud-native microservices, powering everything from Kubernetes to high-frequency trading platforms. But even seasoned Gophers hit the same walls: graceful shutdown races, observability blind spots, and configuration sprawl. This isn't just a list of random snippets—it's a tactical playbook. Each prompt below is designed to be pasted into your AI coding assistant (like Cursor or ASI Biont's agent) to solve a specific, real-world problem. We'll go beyond the basics, referencing official docs and battle-tested patterns, so you can ship resilient services with confidence.
1. The Graceful Shutdown Blueprint
Task: Generate a robust graceful shutdown handler that respects context deadlines and drains in-flight requests.
Prompt:
Act as a senior Go developer. Write a production-ready graceful shutdown implementation for an HTTP server using context.WithTimeout and signal.NotifyContext. Include: 1) a function that listens for SIGINT and SIGTERM, 2) a shutdown method that calls server.Shutdown with a 10-second timeout, 3) proper error logging for shutdown failures, 4) a main() that ties it all together. Use the official net/http and os/signal packages. Add comments explaining each step.
Why it works: This prompt forces the AI to follow Go's official patterns (see the Go blog post "Graceful Shutdown of a Go HTTP Server" from 2014, still canonical). It's specific about the timeout and signals, preventing the common mistake of ignoring context cancellation.
2. The Observability Trinity: Metrics, Logs, Traces
Task: Set up Prometheus metrics, structured logging, and OpenTelemetry tracing in a single service.
Prompt:
Design an observability setup for a Go microservice using OpenTelemetry and Prometheus. Provide code that: 1) initializes a Prometheus histogram for HTTP request duration, 2) sets up a slog logger with JSON output (Go 1.21+), 3) configures an OTLP trace exporter to send spans to a local collector. Include go.mod dependencies with versions (use latest stable). Explain how to correlate logs and traces using trace_id.
Why it works: OpenTelemetry is the CNCF standard, and slog became official in Go 1.21. The prompt asks for concrete versions, reducing hallucination risk. This setup is the foundation for any production service.
3. Configuration Management Without the Sprawl
Task: Create a typed configuration system that reads from env vars and YAML, with validation and defaults.
Prompt:
Write a Go package that loads configuration from a YAML file and environment variables, with environment variables taking precedence. Use struct tags for YAML mapping and implement a Validate() method that checks required fields. Support durations like "10s" for timeouts. Provide a small example with a server port, database URL, and shutdown timeout. Use the viper library or the standard library's encoding/json and os.Getenv—you choose, but justify why.
Why it works: This prompt forces a decision between popular libraries (viper vs. stdlib) and asks for justification, which leads to better, context-aware code. It also includes validation, a step many devs skip.
4. Error Handling: Go 1.20+ Best Practices
Task: Implement error wrapping with context and custom error types.
Prompt:
You are a Go expert. Show me how to use the errors.Join and fmt.Errorf with %w to wrap errors with additional context. Create a custom error type that includes an HTTP status code and an internal code. Demonstrate proper error handling in an HTTP handler that calls a database function, preserving the original error and adding client-friendly messages. Include a test that checks error unwrapping.
Why it works: errors.Join (Go 1.20) is often underused. This prompt surfaces it, plus shows the idiomatic wrapping pattern from the Go blog post "Error handling and Go" (2011). The test requirement ensures the code is verifiable.
5. Concurrency Patterns: Worker Pools and Rate Limiting
Task: Build a worker pool that processes jobs with configurable concurrency and a rate limiter.
Prompt:
Implement a worker pool in Go using goroutines and channels. The pool should accept a slice of jobs, process them concurrently with a specified number of workers, and collect results. Use sync.WaitGroup to wait for completion. Additionally, implement a token bucket rate limiter using golang.org/x/time/rate. Provide a main() that runs the pool with 5 workers and a rate limit of 10 requests per second.
Why it works: This is a classic pattern, and the prompt specifies the exact limits (5 workers, 10 rps), making the output testable. It references the official x/time package, avoiding custom bugs.
6. Database Migrations with golang-migrate
Task: Generate a migration setup for PostgreSQL using golang-migrate.
Prompt:
Write a Go migration script using golang-migrate/migrate. Include: 1) initialization of a migration instance with a PostgreSQL database URL, 2) up and down functions for a table 'users', 3) a CLI command to run migrations. Use the log package for output. Assume the database is already running. Show the full code and the command to execute it.
Why it works: golang-migrate is the de facto tool. The prompt asks for a concrete example, and the CLI command makes it immediately usable.
7. API Design: RESTful with OpenAPI Validation
Task: Create a REST API skeleton with request validation using go-playground/validator.
Prompt:
Create a Go HTTP server that exposes a POST /users endpoint. Use the go-playground/validator package to validate the JSON body: email must be valid, age between 18 and 120. Return 400 with a detailed error message on validation failure. Structure the code with a handler, a service, and a repository layer. Provide go.mod dependencies.
Why it works: This mirrors real-world API design and forces separation of concerns. The validator package is widely used, and the prompt specifies exact validation rules.
8. Testing: Table-Driven Tests and Mocks
Task: Write comprehensive unit tests using the testing package and the testify library.
Prompt:
You are a Go testing expert. Write table-driven tests for a function that calculates the total price of an order including tax. Use the testing package. For a repository interface, create a mock using testify/mock. Include a test that verifies the mock is called with specific arguments. Show the full test file.
Why it works: Table-driven tests are idiomatic (see the Go blog post "TableDrivenTests"). The prompt includes mocks, which are essential for unit testing in microservices.
9. gRPC and Protobuf: From .proto to Service
Task: Generate a gRPC service definition and implementation.
Prompt:
Act as a Go gRPC expert. Define a protobuf file for a UserService with GetUser and CreateUser RPCs. Generate the Go code (mention the protoc command). Then, implement the server side in Go: handle requests, return errors with codes. Include a simple client that calls GetUser. Use the google.golang.org/grpc package. Show the go.mod dependencies.
Why it works: gRPC is heavily used in microservices, and this prompt covers the full workflow. The protoc command is crucial for reproducibility.
10. Context Propagation Across Services
Task: Implement context propagation with OpenTelemetry across HTTP calls.
Prompt:
Write a Go function that makes an HTTP GET request to a downstream service, propagating the current context's trace and span. Use the otelhttp package to wrap the client. Show how to extract trace context from an incoming request and inject it into the outgoing one. Provide a complete example with a middleware for the server side.
Why it works: Distributed tracing is often botched. This prompt uses otelhttp, which automates propagation, and clarifies the extraction/injection process.
11. Dependency Injection Made Simple
Task: Set up dependency injection using wire (Google's tool) or fx.
Prompt:
Compare wire and fx for dependency injection in Go. Choose one and show how to use it to wire a simple service with a database connection, a repository, and an HTTP handler. Include the provider functions and the initialization code. Explain the benefits of compile-time injection versus runtime.
Why it works: DI is a hot topic. This prompt forces a comparison, leading to a thoughtful answer. It also asks for the initialization code, which is the practical part.
12. Security: Secrets Management and TLS
Task: Harden your microservice with secrets injection and TLS configuration.
Prompt:
Write a Go program that reads a database password from an environment variable, but also supports reading from a file (for Docker secrets) using a fallback. Implement a TLS server with a self-signed certificate for development, and use mTLS for service-to-service authentication. Provide the certificate generation commands (openssl) and the Go code.
Why it works: Security is non-negotiable. This prompt covers both env/file secrets and TLS, with concrete openssl commands for reproducibility.
Final Thoughts
These 12 prompts are just the tip of the iceberg. The real magic happens when you adapt them to your specific stack. Start by pasting one into your AI assistant, review the code, and iterate. The more context you provide (your dependencies, your style), the better the output. Go build something resilient!
Comments