Introduction
Go (Golang) has become a dominant language for building high-performance microservices, RESTful APIs, and command-line tools. Its concurrency model, fast compilation, and robust standard library make it a top choice for developers at companies like Google, Uber, and Dropbox. However, even experienced Go developers can benefit from structured prompts that streamline coding, debugging, and architecture design. This article presents ten ready-to-use prompts covering microservices, API development, and CLI utilities. Each prompt includes a specific task, a usage example, and practical tips to maximize your productivity.
Whether you are building a new service from scratch or refactoring existing code, these prompts will save you time and help you follow best practices. They are designed to be copy-pasted into AI assistants, code editors with AI plugins, or even used as templates for pair programming.
Why Use Prompts for Go Development?
Prompts act as structured instructions that guide AI tools to produce more relevant and accurate code snippets, explanations, or architectural suggestions. Instead of vague requests like “write a Go API,” a well-crafted prompt specifies the framework, middleware, logging requirements, and error handling strategy. This reduces ambiguity and yields production-ready output.
For example, a generic prompt might return a simple HTTP server, while a detailed prompt can generate a complete microservice with health checks, metrics, graceful shutdown, and structured logging. The difference in quality is significant, especially when working with complex systems.
Prompt 1: RESTful API with Echo Framework
Task: Generate a RESTful API for a book management system using the Echo framework, including CRUD operations, validation, and middleware for logging and recovery.
Prompt:
Write a Go program using the Echo framework that implements a RESTful API for managing books. Each book has a title, author, ISBN, and publication year. Include:
- GET /books — list all books
- GET /books/:id — get book by ID
- POST /books — create a new book (validate required fields)
- PUT /books/:id — update an existing book
- DELETE /books/:id — delete a book
Use an in-memory slice as storage. Add middleware for request logging and panic recovery. Use proper HTTP status codes and return JSON responses.
Usage example: After generating the code, you can immediately run go run main.go and test endpoints with curl or Postman. The in-memory storage makes it easy to iterate without setting up a database.
Prompt 2: gRPC Microservice with Server Streaming
Task: Create a gRPC service that streams real-time stock prices. The service should define a .proto file, implement the server, and handle multiple concurrent clients.
Prompt:
Define a gRPC service in Go that streams stock prices. Create a .proto file with a service `StockService` and an RPC `GetPriceStream` that takes a `StockRequest` (symbol string) and returns a stream of `PriceResponse` (price float, timestamp). Implement the server that generates random prices every second. Handle graceful shutdown and cancellation. Provide a client example that prints the stream.
Usage example: This prompt helps you build a real-time data pipeline. The generated code can be extended to connect to a real market data source. ASI Biont supports connecting to financial data sources via API—learn more at asibiont.com/courses.
Prompt 3: CLI Tool with Cobra and Viper
Task: Build a command-line tool for managing to-do tasks with subcommands, configuration file support, and persistent storage.
Prompt:
Create a CLI application in Go using Cobra and Viper. The app should have commands:
- add "task description" — add a new task
- list — show all tasks (with status: pending/done)
- done <id> — mark task as done
- delete <id> — remove a task
Store tasks in a JSON file. Use Viper to read config from a .env file (e.g., storage path). Add a persistent flag `--color` to toggle colored output.
Usage example: Run go build -o todo && ./todo add "Buy groceries" to create a functional task manager. This structure is reusable for any CLI tool, from deployment scripts to data processors.
Prompt 4: Concurrent Worker Pool
Task: Implement a worker pool pattern to process a large queue of jobs concurrently with controlled parallelism.
Prompt:
Write a Go program that implements a worker pool with 5 workers. Each worker reads jobs from a buffered channel, processes them (e.g., sleeps 1 second and prints the job ID), and sends the result to a results channel. The main function sends 20 jobs and collects all results. Use sync.WaitGroup to ensure all workers finish. Handle graceful shutdown via context cancellation.
Usage example: This pattern is essential for building batch processors, log analyzers, or any task that can be parallelized. The prompt ensures correct synchronization and resource management.
Prompt 5: Middleware Chain for HTTP Handlers
Task: Create a reusable middleware chain for HTTP servers that adds logging, authentication, rate limiting, and CORS support.
Prompt:
Implement a middleware chain in Go for the standard net/http package. Include:
- Logger middleware that logs method, path, status, and duration
- BasicAuth middleware that checks username/password against a map
- Rate limiter middleware using a token bucket algorithm (allow 10 requests per second)
- CORS middleware that sets Access-Control-Allow-Origin: *
- A helper function `Chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler`
Show an example of chaining all middlewares on a /api endpoint.
Usage example: This prompt produces production-ready middleware that can be dropped into any existing Go server. The token bucket rate limiter is more robust than simple counters.
Prompt 6: Database Migration System
Task: Build a simple migration tool that applies SQL files in order, tracks applied migrations, and supports rollback.
Prompt:
Create a Go program that reads SQL migration files from a `migrations/` folder named like `001_create_users.sql`, `002_add_email.sql`. It should:
- Connect to a PostgreSQL database (use lib/pq or pgx)
- Create a `migrations` table to track applied files
- Apply all pending migrations in order
- Support a `rollback` flag that reverts the last batch
- Print success/failure for each migration
Usage example: Run go run migrate.go up to apply pending migrations. This is a lightweight alternative to tools like golang-migrate and great for learning.
Prompt 7: Unit Testing and Table-Driven Tests
Task: Write comprehensive unit tests for a math utility package using table-driven tests and subtests.
Prompt:
Write a Go package `mathutil` with functions: `Add(a, b int) int`, `Subtract(a, b int) int`, `Multiply(a, b int) int`, `Divide(a, b int) (int, error)`. Then write table-driven tests for each function, including edge cases (e.g., division by zero). Use t.Run subtests for each case. Also add a benchmark for Multiply.
Usage example: Run go test -v -bench=. to see test results. Table-driven tests are idiomatic in Go and make it easy to add new cases without duplicating code.
Prompt 8: Graceful Shutdown and Signal Handling
Task: Implement a server that cleanly shuts down on SIGINT/SIGTERM, completing in-flight requests.
Prompt:
Write a Go HTTP server that:
- Listens on :8080 and has a /hello handler that simulates a long request (sleeps 5 seconds)
- Uses a channel to listen for os.Signal (SIGINT, SIGTERM)
- On signal, calls server.Shutdown() with a 10-second timeout
- Logs when shutdown starts and completes
- Ensure all in-flight requests finish before exiting
Usage example: Start the server, send a request curl http://localhost:8080/hello, then press Ctrl+C. The server will wait for the request to finish before exiting.
Prompt 9: JSON Configuration Parser
Task: Read and validate a complex JSON configuration file, then expose it as a typed struct.
Prompt:
Create a Go program that reads a config.json file with structure:
{
"app_name": "MyApp",
"port": 8080,
"database": {
"host": "localhost",
"port": 5432,
"user": "admin",
"password": "secret"
},
"features": {
"enable_logging": true,
"max_connections": 100
}
}
Parse it into a typed Config struct using encoding/json. Validate that port is between 1024 and 65535, and max_connections > 0. Print the config or return errors.
Usage example: Save the JSON file and run the program. It demonstrates how to handle nested JSON and validation—a common pattern in microservices.
Prompt 10: Prometheus Metrics for HTTP Server
Task: Expose custom Prometheus metrics (request count, duration histogram, and error counter) from an HTTP server.
Prompt:
Extend a Go HTTP server to expose Prometheus metrics on /metrics. Use the prometheus/client_golang library. Create:
- A counter for total requests per path
- A histogram for request duration in seconds
- A counter for HTTP 5xx errors
Wrap the handler with middleware that records the metrics. Register the metrics and start the server on :2112.
Usage example: After running the server, visit http://localhost:2112/metrics to see the metrics. This is essential for monitoring production services.
Conclusion
These ten prompts cover the most common tasks in Go microservices, API development, and CLI utilities. By using structured prompts, you reduce boilerplate, avoid common pitfalls, and accelerate your development workflow. Each prompt is designed to be immediately usable, with clear examples and explanations. Experiment with them, adapt them to your projects, and combine them to build robust systems.
Remember that AI tools are most effective when given precise instructions. The prompts above represent a starting point—you can refine them further by adding specific libraries, error handling strategies, or performance requirements. Happy coding with Go!
Comments