You know that feeling when you're staring at a Go codebase, and you know exactly what you want to do—spin up a REST API, handle concurrency like a pro, or write a Kafka consumer—but you're stuck on the boilerplate? Or maybe you've written the same net/http handler for the hundredth time and think, "There has to be a better way." Well, there is. This isn't just another list of AI prompts; it's a survival kit for Go developers, from someone who's been in the trenches. I've curated 15 prompts that tackle real-world challenges, from generating idiomatic REST handlers to debugging data races in your goroutines. Each prompt is crafted to get you from problem to production-ready code faster, and I've included concrete examples and output samples so you know exactly what to expect.
Why Prompts for Go? Because the Ecosystem Demands It
Go's philosophy is simple: less magic, more clarity. But that doesn't mean writing it is always straightforward. The standard library is powerful, but it's also verbose. The ecosystem—with tools like chi, sqlc, and franz-go—adds its own conventions. A good prompt acts like a senior developer looking over your shoulder, reminding you of best practices and saving you from hours of digging through docs. According to the Go Developer Survey 2024, 89% of respondents said they use Go for backend development, and a significant portion struggle with concurrency and API design. These prompts are designed to address those exact pain points.
Prompt 1: Generating an Idiomatic REST API with Middleware
Task: Generate a fully functional REST API in Go using the standard library, complete with middleware for logging, recovery, and CORS, plus proper JSON response handling.
Prompt:
Generate a Go REST API server using the standard library (net/http) that:
- Has endpoints for CRUD operations on a "Task" resource (GET /tasks, GET /tasks/{id}, POST /tasks, PUT /tasks/{id}, DELETE /tasks/{id}).
- Stores tasks in memory with a mutex for thread safety.
- Uses a custom middleware chain for logging, panic recovery, and CORS.
- Returns JSON responses with proper status codes (200, 201, 404, 405).
- Uses gorilla/mux for routing (or suggest chi).
- Include a main.go file and a README with usage instructions.
Example Result:
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/mux"
)
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
CreatedAt time.Time `json:"created_at"`
}
type TaskStore struct {
sync.RWMutex
tasks map[string]Task
}
func (s *TaskStore) Create(t Task) {
s.Lock()
defer s.Unlock()
s.tasks[t.ID] = t
}
// ... other methods
func main() {
store := &TaskStore{tasks: make(map[string]Task)}
r := mux.NewRouter()
r.Use(loggingMiddleware, recoveryMiddleware, corsMiddleware)
// ... route registrations
log.Fatal(http.ListenAndServe(":8080", r))
}
This prompt gives you a solid foundation, and you can iterate from there.
Prompt 2: Refactoring God Functions into Clean Handlers
Task: Break down a large, monolithic HTTP handler into small, testable units.
Prompt:
Refactor this Go HTTP handler into smaller, testable functions. The current code is a 200-line monolith that does authentication, validation, database access, and response formatting all in one place. Suggest a structure using the Repository pattern and show how to write unit tests for the extracted functions.
[Paste the existing code]
Example Result: The AI should output a breakdown like:
parseRequestfor decoding and validating the request bodyauthenticatefor checking the JWT tokentaskRepositorywith methods likeGetByIDandCreatewriteResponsefor consistent JSON output
This approach aligns with Go's idiomatic style and improves maintainability.
Prompt 3: Optimizing Goroutine Usage with Worker Pools
Task: Implement a worker pool to process a large number of tasks concurrently, avoiding goroutine leaks.
Prompt:
Write a Go program that processes a list of URLs concurrently using a worker pool. The pool should have a fixed number of workers (e.g., 5). Each worker fetches the URL and calculates the response time. Use channels for task distribution and result collection. Ensure that the program waits for all workers to finish and handles errors gracefully.
Example Result:
func worker(id int, jobs <-chan string, results chan<- time.Duration) {
for url := range jobs {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
log.Printf("worker %d: %v", id, err)
continue
}
resp.Body.Close()
results <- time.Since(start)
}
}
This is a classic pattern, and the prompt ensures you get the channel semantics right.
Prompt 4: Writing Table-Driven Tests with Mocks
Task: Generate table-driven tests for a function that computes the total price of an order, including mocking an external service.
Prompt:
Write table-driven tests for a Go function `CalculateTotal(price float64, quantity int) (float64, error)` that applies a discount based on quantity. Include test cases for edge cases (negative price, zero quantity, high quantity). Also, write a test for a function that calls an external API, using a mock HTTP server.
Example Result:
func TestCalculateTotal(t *testing.T) {
tests := []struct {
name string
price float64
quantity int
want float64
wantErr bool
}{
{"normal", 10.0, 2, 20.0, false},
{"zero quantity", 10.0, 0, 0, true},
{"negative price", -5.0, 1, 0, true},
}
// ... loop and run
}
Table-driven tests are the Go way, and this prompt ensures you cover all bases.
Prompt 5: Debugging Data Races with the Race Detector
Task: Identify and fix data races in a given Go program.
Prompt:
Here's a Go program that has a data race. Explain what the race condition is, how to detect it using `go run -race`, and provide the corrected code.
[Paste buggy code]
Example Result: The AI will explain that the race occurs because multiple goroutines access a shared map without synchronization, and suggest using a sync.Mutex or sync.RWMutex. It will also mention the -race flag and how to interpret the output.
Prompt 6: Generating a Kafka Consumer with Proper Offset Handling
Task: Create a Kafka consumer using the franz-go library that reads messages from a topic, processes them, and commits offsets correctly.
Prompt:
Write a Go Kafka consumer using the `github.com/twmb/franz-go/pkg/kgo` library. It should:
- Connect to a broker at localhost:9092.
- Subscribe to the topic "orders".
- Process each message by logging it and possibly sending to a database.
- Handle errors and retries.
- Commit offsets manually after successful processing.
- Gracefully handle shutdown signals.
Example Result:
// ... setup client with kgo.NewClient
for {
fetches := client.PollFetches(context.Background())
if errs := fetches.Errors(); len(errs) > 0 {
// handle
}
fetches.EachRecord(func(record *kgo.Record) {
// process
client.CommitRecords(context.Background(), record)
})
}
This prompt gives you a production-ready pattern.
Prompt 7: Building a gRPC Server and Client with Protobuf
Task: Generate a gRPC service definition and the corresponding Go server and client code.
Prompt:
Create a gRPC service for a user management system. Define a protobuf file with messages `User`, `GetUserRequest`, `CreateUserRequest`, and a service `UserService` with methods `GetUser` and `CreateUser`. Then generate the Go code using `protoc` and provide a simple client/server implementation.
Example Result: The AI will provide the .proto file, the command to generate code, and a basic server that implements the interface.
Prompt 8: SQLC Integration for Type-Safe Database Operations
Task: Integrate sqlc to generate type-safe Go code from SQL queries.
Prompt:
I have a PostgreSQL database with a table `users`. Write a SQL query to get a user by email, and show how to configure `sqlc` to generate Go code. Then, write a Go function that uses the generated code to fetch and return the user.
Example Result: The AI will output the schema.sql, query.sql, sqlc.yaml, and the generated Go code snippet.
Prompt 9: Implementing Graceful Shutdown for HTTP Servers
Task: Add graceful shutdown to an existing Go HTTP server.
Prompt:
Modify this Go HTTP server to support graceful shutdown on SIGINT and SIGTERM. Include a timeout for in-flight requests and log when the server is shutting down.
[Paste existing code]
Example Result: The AI will show you how to use signal.NotifyContext and http.Server.Shutdown with a context timeout.
Prompt 10: Generating OpenAPI Documentation from Code
Task: Generate an OpenAPI specification for a REST API from comments in the code.
Prompt:
Given this Go code for a REST API, generate OpenAPI 3.0 documentation using the `swaggo/swag` library. Add the necessary annotations to the handler functions and show how to run `swag init`.
[Paste code]
Example Result: The AI will show you the comments to add, like @Summary, @Tags, @Accept, @Produce, and the resulting swagger.yaml.
Prompt 11: Enhancing Performance with Context and Cancellation
Task: Rewrite a function to use context for cancellation and timeouts.
Prompt:
Refactor this Go function that makes an HTTP request to use `context.WithTimeout`. Also, show how to propagate the context to the request and handle the case where the operation is canceled.
Example Result: The AI will produce code using http.NewRequestWithContext and check for context.DeadlineExceeded.
Prompt 12: Writing a CLI Tool with Cobra
Task: Create a command-line interface (CLI) application using cobra.
Prompt:
Build a CLI tool called `taskctl` that manages a to-do list. It should have commands like `add`, `list`, `done`, and `delete`. Use `cobra` for the command structure and store tasks in a JSON file. Provide the full main.go and command files.
Example Result: The AI will generate a complete cobra command structure with subcommands and file-based storage.
Prompt 13: Implementing Rate Limiting with golang.org/x/time
Task: Add rate limiting to an HTTP handler using the golang.org/x/time/rate package.
Prompt:
Write a Go middleware that limits requests to 10 per second per IP address. Use the `golang.org/x/time/rate` package and a map to track IPs. Include cleanup for old entries.
Example Result: The AI will show you how to create a rate.Limiter per IP and lock the map with a mutex.
Prompt 14: Comparing JSON vs. Protocol Buffers for Microservices
Task: Compare JSON and Protocol Buffers for inter-service communication.
Prompt:
Explain the performance and size differences between JSON and Protocol Buffers in Go microservices. Provide a benchmark example using `benchstat` or a simple test that measures serialization time and message size.
Example Result: The AI will discuss the binary format of protobuf, its efficiency, and show a benchmark code snippet. It might reference the official protobuf documentation at protobuf.dev.
Prompt 15: Building a Chat Application with WebSockets
Task: Implement a simple WebSocket chat server using gorilla/websocket.
Prompt:
Write a Go WebSocket server that allows multiple clients to connect and broadcast messages to all connected clients. Handle client disconnections and ensure thread safety. Provide the server code and a minimal HTML client for testing.
Example Result: The AI will provide a hub pattern with channels for broadcast, and a simple HTML page with JavaScript to connect.
The Road Ahead: Making Prompts Your Own
These prompts are not just copy-paste solutions; they're starting points. The real power comes when you adapt them to your specific context. For example, I once used a similar prompt to generate a Kafka consumer for a logistics company, and the AI's suggestion to use franz-go instead of the heavier confluent-kafka-go saved us a ton of memory. As the Go ecosystem evolves—with features like generics and the new slog package—prompts can help you stay ahead. The key is to treat AI as a collaborator, not a replacement. So, next time you're stuck on a goroutine leak or a tricky gRPC setup, frame your problem into a prompt, and see what you get. You might be surprised at how much time you save. Now go build something great, and don't forget to run go vet before you commit!
Comments