Go is a language designed for scalable microservices, and every Go developer knows: routine eats time. Boilerplate, debugging concurrency, profiling — all of this can be accelerated with AI. I've collected 12 prompts that I actually use in my work. They save me hours every week, and I'm sure they'll be useful to you too.
1. Generating Microservice Boilerplate
Prompt: "Generate a Go microservice structure with a REST API using the standard net/http library. Include a health-check endpoint, graceful shutdown, and basic logging. Put the code in a main.go file."
Why: Writing the skeleton from scratch takes 20 minutes; AI does it in 1 minute. You get a working start that you can commit immediately.
Example:
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
go func() {
log.Println("Server starting on :8080")
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server forced to shutdown:", err)
}
log.Println("Server exiting")
}
Result: Save 20 minutes on each new service. In a team of 5, that's 100 minutes per week.
2. Performance Optimization: Finding Bottlenecks
Prompt: "Here's a Go function that processes a slice of structs. Find possible optimizations: avoiding allocations, improving cache locality, using sync.Pool if applicable. Source code: [paste code]"
Why: AI helps find non-obvious issues like unnecessary copies or inefficient loops. This is especially useful for high-load systems where every microsecond counts.
Example: Suppose you have a function that sums fields of structs. AI will suggest iterating over pointers to avoid copying and pre-calculating slice length.
Result: 2-3x speedup on large data. In one of my projects, this reduced API latency from 500ms to 180ms.
3. Refactoring Legacy Code
Prompt: "Help refactor this Go code: split the monolithic file into packages, improve variable naming, add comments for exported functions. Code: [paste code]"
Why: Refactoring is scary, but AI makes it safe by suggesting incremental changes. You can review each change and apply only what you need.
Example: Once I had a 2000-line file with global variables. AI suggested splitting it into three packages: models, storage, and handlers. I applied the changes, and tests passed without a single edit.
Result: Reduced code coupling, improved readability. An hour of work instead of a whole day.
4. Writing Unit Tests with Cases
Prompt: "Write unit tests for this Go function using table-driven tests. Cover edge cases: empty input, nil, large values. Function: [paste code]"
Why: Tests are boring but necessary. AI generates entire tables with cases you might not have considered. This increases coverage and reliability.
Example:
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive", 2, 3, 5},
{"negative", -1, -2, -3},
{"zero", 0, 0, 0},
{"overflow", math.MaxInt, 1, math.MinInt},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add() = %v, want %v", got, tt.want)
}
})
}
}
Result: Test coverage from 30% to 90% in half an hour. Fewer bugs in production.
5. Designing Concurrency Patterns
Prompt: "Design concurrent task processing in Go using a worker pool. Explain how to limit the number of goroutines and handle errors. Provide code."
Why: Concurrency is powerful, but easy to trip up. AI generates proven patterns, like a worker pool with channels and context.
Example:
func worker(ctx context.Context, jobs <-chan Job, results chan<- Result) {
for {
select {
case job, ok := <-jobs:
if !ok {
return
}
results <- process(job)
case <-ctx.Done():
return
}
}
}
func run(ctx context.Context, jobs []Job) []Result {
const numWorkers = 10
jobsCh := make(chan Job)
resultsCh := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
worker(ctx, jobsCh, resultsCh)
}()
}
go func() {
defer close(jobsCh)
for _, j := range jobs {
select {
case jobsCh <- j:
case <-ctx.Done():
return
}
}
}()
go func() {
wg.Wait()
close(resultsCh)
}()
var results []Result
for r := range resultsCh {
results = append(results, r)
}
return results
}
Result: Proper cancellation handling and no goroutine leaks. Saves time debugging deadlocks.
6. Working with Channels and select
Prompt: "Explain the difference between buffered and unbuffered channels in Go. Provide examples of when to use each. Also show how select with default helps avoid blocking."
Why: Even experienced developers get confused with channels. AI gives clear explanations and examples you can use immediately.
Example:
// Buffered channel: send doesn't block until buffer is full
ch := make(chan int, 2)
ch <- 1
ch <- 2 // doesn't block
// select with default: non-blocking check
select {
case msg := <-ch:
fmt.Println(msg)
case <-time.After(1 * time.Second):
fmt.Println("timeout")
default:
fmt.Println("no message")
}
Result: Deep understanding of concurrency. Fewer errors in production.
7. Error Handling: Panic and Recover
Prompt: "Write an example of safe panic handling in Go using defer and recover. Explain when this is better than returning errors."
Why: Panic is an exceptional situation, but sometimes you need to catch it, e.g., in goroutines. AI shows how to do it correctly.
Example:
func safeCall(f func()) {
defer func() {
if r := recover(); r != nil {
log.Printf("Recovered from panic: %v", r)
}
}()
f()
}
func main() {
safeCall(func() {
panic("something bad")
})
fmt.Println("program continues")
}
Result: Service stability even with unexpected errors.
8. Generating Code for JSON Handling
Prompt: "Generate Go structs for the following JSON using encoding/json. Add tags for correct mapping and methods for validation. JSON: [paste JSON]"
Why: Writing structs manually for complex JSON is tedious. AI does it quickly and without errors.
Example:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}
func (u *User) Validate() error {
if u.Name == "" {
return errors.New("name is required")
}
if u.Email == "" {
return errors.New("email is required")
}
return nil
}
Result: Accurate API matching and fewer decoding errors.
9. Optimizing Memory Usage
Prompt: "Analyze this Go code for heap allocations. Suggest changes to reduce the number of allocations. Code: [paste code]"
Why: In high-load systems, allocations kill performance. AI finds where to use values instead of pointers or reuse buffers.
Example: AI might suggest using sync.Pool for temporary objects.
Result: Reduced GC pressure, improved throughput.
10. Profiling with pprof
Prompt: "How to use pprof in Go for CPU and memory profiling? Write an example of how to add pprof to an HTTP server and how to run analysis."
Why: Profiling is key to optimization. AI explains how to enable pprof and interpret results.
Example:
import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// ... rest of code
}
Then run go tool pprof http://localhost:6060/debug/pprof/profile. AI can also help analyze the output.
Result: Quickly find bottlenecks. I once found a function that took 80% CPU and optimized it in an evening.
11. Automating Documentation
Prompt: "Generate documentation in GoDoc format for the following exported functions. Describe parameters, return values, and possible errors."
Why: Documentation is something everyone puts off. AI writes it for you, and it always matches the code.
Example:
// Add sums two integers.
// Returns the sum and an error if overflow occurs.
func Add(a, b int) (int, error) {
if a > math.MaxInt-b {
return 0, errors.New("overflow")
}
return a + b, nil
}
Result: Clean documentation without effort.
12. AI-Powered Code Review
Prompt: "Conduct a code review of this Go code. Find potential issues: data races, goroutine leaks, incorrect error handling. Suggest fixes."
Why: A second opinion never hurts. AI finds things you might have missed.
Example: AI might notice you forgot to close a channel or didn't check an error from json.Unmarshal.
Result: Better code quality before merge.
Conclusion
These 12 prompts are my daily arsenal. They don't replace thinking, but they speed up routine, allowing you to focus on architecture. Start with boilerplate generation and tests — that will bring quick results. And remember: AI is a tool, not a replacement. Always check generated code, especially in concurrent scenarios.
Want more collections like this? Subscribe to the blog to not miss new materials on Go and AI. And if you have your own favorite prompts — share in the comments, let's discuss!
Comments