21 Prompts for Go: Microservices, APIs, and CLI Utilities

Introduction

Go (Golang) has become a dominant language for building backend systems, from high-performance APIs and microservices to command-line tools that DevOps teams rely on daily. Its simplicity, built-in concurrency, and fast compilation make it a favorite among engineers at companies like Google, Uber, and Dropbox. However, even experienced Go developers often waste time on repetitive boilerplate, debugging, and architecture decisions. This is where AI-powered prompts come in — they act as a force multiplier, helping you generate code, refactor logic, and design systems faster.

This article is a curated collection of 21 battle-tested prompts for Go development. Each prompt is designed to solve a real-world problem: generating a REST API handler, structuring a microservice with clean architecture, writing a CLI tool with Cobra, or optimizing database queries. You can copy these prompts directly into ChatGPT, Claude, or your preferred AI assistant. I’ve tested all of them in my workflow — they produce working, idiomatic Go code that follows best practices. Let’s dive in.

Why Use Prompts for Go Development?

Before we list the prompts, it’s worth understanding why a prompt-based approach works so well for Go. According to the Go Developer Survey 2024 (Go blog), 89% of respondents use Go for backend development, and 76% build APIs or microservices. The language’s strong typing and explicit error handling mean that AI-generated code is often more predictable than in dynamic languages. Prompts help you:

  • Reduce boilerplate: Go’s if err != nil pattern can be tedious. Prompts generate complete error-handling blocks.
  • Enforce conventions: AI can output code that follows the Go Proverbs and uses standard library idioms.
  • Accelerate prototyping: Generate a full CRUD API in seconds, then iterate.

Essential Prompts for Go Development

1. Generate a REST API Handler with net/http

Prompt:
"Write a Go HTTP handler for a REST API endpoint that accepts a POST request with a JSON body containing fields name and email. The handler should validate that both fields are non-empty, return a 400 error with a JSON message if validation fails, and return a 201 status with a JSON success message. Use only the standard net/http and encoding/json packages. Handle errors explicitly."

Usage example: Paste this when you need a quick handler without frameworks. It produces production-ready validation.

2. Structuring a Microservice with Clean Architecture

Prompt:
"Create a Go project structure for a microservice that follows Clean Architecture. Include directories for domain, usecase, repository, delivery, and config. For each layer, provide a brief comment explaining its responsibility. Then generate a sample User entity in the domain layer, a UserRepository interface, and a UserUsecase implementation."

Usage example: Use this when starting a new service. The AI will output a folder layout and interface definitions that keep your business logic independent of frameworks.

3. CLI Tool with Cobra

Prompt:
"Write a CLI tool in Go using the Cobra library that has three commands: init, run, and status. The init command should accept a --config flag (default: config.yaml). The run command should execute a function that prints 'Running...' to stdout. The status command should print 'OK'. Include proper error handling and a root command with a description. Use github.com/spf13/cobra."

Usage example: Ideal for DevOps utilities or custom automation scripts. Cobra is the de facto standard for Go CLIs.

4. Database Migration Script

Prompt:
"Generate a Go function that reads a SQL migration file from disk, executes it against a PostgreSQL database using the database/sql package and lib/pq driver. The function should accept a *sql.DB connection and a file path. It should log each statement before execution and roll back the entire transaction if any statement fails. Use log.Fatal only for unrecoverable errors."

Usage example: Plug this into your CI/CD pipeline for database schema changes.

5. HTTP Client with Retry Logic

Prompt:
"Write a Go function that makes an HTTP GET request to a given URL with a timeout of 5 seconds. If the request fails (network error or non-2xx status code), retry up to 3 times with exponential backoff (base delay 1 second). Use the net/http and math/rand packages. Return the response body as a string and any error. Log each retry attempt."

Usage example: Useful for integrating with external APIs that may be unreliable.

6. Context Propagation in Microservices

Prompt:
"Explain how to propagate a context.Context with a request ID and user ID through multiple layers in a Go microservice. Provide a code example showing how to extract these values from the HTTP request, store them in context, pass them to a use case, and then to a repository. Use middleware for context setup."

Usage example: Ensures traceability across service boundaries.

7. Testing with Table-Driven Tests

Prompt:
"Write a table-driven test in Go for a function Add(a, b int) int. The test should include at least five test cases: normal addition, negative numbers, zero, overflow (if applicable), and large numbers. Use the testing package. Show how to run the test and what the output looks like."

Usage example: Copy this pattern for any function you need to test thoroughly.

8. JSON Web Token (JWT) Middleware

Prompt:
"Write a Go HTTP middleware that validates a JWT token from the Authorization header. The middleware should extract the Bearer token, verify it using a secret key (HS256), parse the claims (user ID and role), and store them in the request context. If the token is invalid or missing, return a 401 error. Use github.com/golang-jwt/jwt/v5."

Usage example: Secure your API endpoints with minimal code.

9. Graceful Shutdown

Prompt:
"Write a Go program that starts an HTTP server on port 8080 and handles graceful shutdown on SIGINT or SIGTERM. Use a context.Context with a timeout of 10 seconds. Ensure all in-flight requests complete before the server exits. Log the shutdown process."

Usage example: Essential for production services to avoid dropping requests.

10. Concurrency with Worker Pool

Prompt:
"Implement a worker pool in Go using goroutines and channels. The pool should have a fixed number of workers (e.g., 5). Workers receive jobs from a channel, process them (simulate with time.Sleep), and send results to a results channel. The main function sends 20 jobs and prints each result. Use sync.WaitGroup to wait for all workers to finish."

Usage example: Process batches of tasks like image resizing or log parsing.

11. Configuration Loading from Environment Variables

Prompt:
"Write a Go function that loads configuration from environment variables into a struct using the os package. The struct should have fields: Port (int, default 8080), DatabaseURL (string, required), Debug (bool, default false). Validate that required fields are set. Return an error if validation fails."

Usage example: Replace heavy config libraries with a lightweight approach.

12. GraphQL Resolver

Prompt:
"Write a Go GraphQL resolver for a Query type that returns a list of users. Use github.com/graphql-go/graphql. The resolver should call a UserRepository method FindAll(). The user type has fields id, name, email. Provide the schema definition and the resolver function."

Usage example: Build GraphQL APIs with Go without a full framework.

13. Middleware for Request Logging

Prompt:
"Create an HTTP middleware in Go that logs each incoming request: method, path, status code, and duration. Use the standard log package. Wrap the http.Handler and use a responseWriter wrapper to capture the status code. Test with a simple handler."

Usage example: Add to any server for observability.

14. Rate Limiting Middleware

Prompt:
"Write a token bucket rate limiter middleware in Go. It should allow a configurable number of requests per second (e.g., 10) and a burst size (e.g., 20). If the limit is exceeded, return 429 Too Many Requests with a JSON error message. Use sync.Mutex for thread safety."

Usage example: Protect your API from abuse.

15. File Watcher Utility

Prompt:
"Write a Go program that watches a directory for new .txt files using the fsnotify package. When a new file appears, read its content and print it to stdout. Ignore subdirectories. Handle errors gracefully and run indefinitely until interrupted."

Usage example: Automate file processing pipelines.

16. SQL Query Builder

Prompt:
"Write a Go function that builds a SELECT query dynamically from a struct. The struct has fields Name, Email, Age with db tags. The function should accept a table name and a map of conditions (field name to value). Return the query string and arguments. Use fmt.Sprintf with parameterized placeholders."

Usage example: Avoid ORM overhead for simple queries.

17. Health Check Endpoint

Prompt:
"Write a Go HTTP handler for a /health endpoint that returns JSON with status 'ok' and the current timestamp. The handler should also check database connectivity (simulate with a ping to a *sql.DB). If the ping fails, return a 503 status with an error message."

Usage example: Required for Kubernetes liveness probes.

18. API Client for External Service

Prompt:
"Generate a Go client for the GitHub API that fetches a user's repositories. Use the net/http package. The client should accept a GitHub token for authentication, handle pagination (max 100 repos per page), and return a slice of structs with Name, Stars, and Language. Include error handling for rate limits."

Usage example: Integrate with any REST API programmatically.

19. JSON Pretty Printer for CLI

Prompt:
"Write a Go CLI tool that reads JSON from stdin, validates it, and prints it with indentation. Use the encoding/json package. If the input is invalid, print a clear error message. Support a --compact flag to output without indentation."

Usage example: Useful in shell pipelines for debugging.

20. Memory Cache with TTL

Prompt:
"Implement a thread-safe in-memory cache in Go with TTL (time-to-live) expiration. The cache should support Set(key, value, ttl), Get(key), and Delete(key) methods. Use a background goroutine to clean expired keys every minute. Use sync.RWMutex for concurrent access."

Usage example: Cache database query results or API responses.

21. Error Wrapping and Stack Traces

Prompt:
"Write a Go package that provides custom error types with stack traces. Use runtime.Callers to capture the stack. Include functions Wrap(err error, message string) and Unwrap(err error) error. Show how to use it in a function that calls another function, printing the stack trace on error."

Usage example: Debug production issues faster.

Best Practices for Using Prompts with Go

  • Always review generated code: AI can produce code that compiles but has logical errors. Run go vet and golint.
  • Prefer standard library: Many prompts use net/http instead of Gin or Echo. This reduces dependencies and keeps your codebase lean.
  • Use prompts for scaffolding: Generate the skeleton, then manually add business logic. This balances speed with control.

Conclusion

These 21 prompts cover the most common tasks in Go development: from building REST APIs and microservices to writing CLI utilities and tests. By integrating AI prompts into your workflow, you can cut down development time significantly — imagine generating a fully functional HTTP handler with validation in under a minute. However, always remember that AI is a tool, not a replacement for understanding. Use these prompts as a starting point, then customize and harden the code for your specific use case.

To further streamline your Go projects, consider using a platform that integrates with external APIs and databases effortlessly. ASI Biont supports connecting to various services through API — learn more at asibiont.com/courses.

← All posts

Comments