ShortIQ

ShortIQ

AI

50 AI Prompts for Go (Golang) Backend Development

50 practical AI prompts for Go developers. Covers project setup, HTTP servers with net/http and Gin, database access with sqlx, concurrency patterns, gRPC, testing, Docker, and deploying Go services to production.

June 16, 2026ShortIQ Editorial Team

How to Use These Go Prompts

Go is a statically typed, compiled language designed for high-performance backend services. It produces single statically linked binaries, has exceptional concurrency primitives, and is the language behind Docker, Kubernetes, and many of the most performant backend systems in production today. These 50 prompts cover the Go development lifecycle from project setup to production deployment.

All prompts assume Go 1.22 or later. When using them, always specify your Go module name (go.mod module declaration) and which web framework you are using — Gin is the most popular choice, but many production Go services use the standard library net/http or more recent alternatives like Chi or Echo. For database prompts, specify PostgreSQL with pgx or sqlx as the most common stack.

Project Setup, HTTP Servers, and Routing (Prompts 1-14)

Prompt 1: Create a new Go module for a REST API service. Show the directory structure: cmd/api/main.go as the entry point, internal/handler for HTTP handlers, internal/service for business logic, internal/repository for database access, and internal/model for domain types. Write the main.go that initialises the database connection, wires dependencies, creates the HTTP server, and handles graceful shutdown on SIGINT and SIGTERM.

Prompt 2: Write a Gin HTTP server with structured error handling. Define a standard API response envelope with data, error, and meta fields. Write a middleware that catches panics and returns a 500 JSON response. Write a helper function that converts service errors to HTTP status codes — ErrNotFound to 404, ErrValidation to 400, ErrUnauthorized to 401 — and returns the correct JSON error body. Prompt 3: Create a Go HTTP router using the standard library net/http ServeMux (Go 1.22+). Register routes for GET /api/users, POST /api/users, GET /api/users/{id}, PATCH /api/users/{id}, and DELETE /api/users/{id} using the new pattern syntax with method prefix. Show how to extract path parameters from r.PathValue.

  • Prompt 4: Write a Go middleware chain for a Gin server. Implement a request ID middleware that generates a UUID and adds it to the context and response header, a structured logging middleware using slog that logs method, path, status, and duration for every request, and a rate limiting middleware using a token bucket per IP address.
  • Prompt 5: Create a Go request validation setup using the go-playground/validator package. Define a CreateUserRequest struct with binding tags for required fields, email format, and min/max length. Write a generic bindAndValidate helper that decodes the JSON body, validates the struct, and returns a structured validation error listing all invalid fields.
  • Prompt 6: Write a Go file upload handler that accepts a multipart form upload, validates the file type by reading the first 512 bytes and checking the MIME type, limits the upload to 10MB, saves the file to a local temp directory, uploads it to S3 using the AWS SDK v2, and returns the object URL.
  • Prompt 7: Create a Go WebSocket server using gorilla/websocket. Handle the upgrade from HTTP, maintain a list of connected clients in a hub struct, broadcast messages from one client to all others, handle disconnection cleanly, and show the goroutine-safe client map pattern.
  • Prompt 8: Write a Go server-sent events (SSE) endpoint. Keep the HTTP connection open, send periodic heartbeat comments to prevent proxy timeouts, write typed event data as JSON, and close the stream when the client disconnects (detect via r.Context().Done()).
  • Prompt 9: Create a Go HTTP client with sensible production defaults. Set a 30-second timeout, configure connection pooling with MaxIdleConns and MaxIdleConnsPerHost, add a retry function with exponential backoff for 5xx errors and network errors, and add a request ID header to every outgoing request.
  • Prompt 10: Write a Go health check endpoint that returns database ping status, external dependency status, and uptime. Return 200 if all checks pass and 503 if any check fails. Format the response as JSON with each check named, its status (ok or degraded), and its latency in milliseconds.
  • Prompt 11: Create a Go configuration loader using environment variables and a YAML config file. Use the viper package to read from both sources with env vars taking precedence, validate required fields are present on startup, and expose a typed Config struct to the rest of the application.
  • Prompt 12: Write a Go graceful shutdown pattern. On SIGINT or SIGTERM, stop accepting new connections, wait up to 30 seconds for in-flight requests to complete using http.Server.Shutdown, close the database connection pool, flush the logger, and exit with code 0 on clean shutdown or code 1 on timeout.
  • Prompt 13: Create a Go OpenAPI documentation setup using swaggo/swag. Add Swagger annotations to handler functions for a User CRUD API, generate the swagger.json with go generate, serve the Swagger UI at /docs, and show how to add Bearer token authentication to the Swagger UI.
  • Prompt 14: Write a Go CORS middleware for a Gin server. Allow specific origins from a configurable list, handle preflight OPTIONS requests with the correct Allow-Headers and Allow-Methods, set the correct Access-Control-Allow-Credentials header for authenticated requests, and reject origins not on the allowlist.

Database, Concurrency, gRPC, and Testing (Prompts 15-50)

Prompt 15: Write a Go PostgreSQL repository using pgx/v5. Define a UserRepository with FindByID, List, Create, Update, and Delete methods. Use pgxpool for connection pooling, use pgx named arguments for query parameters to prevent SQL injection, scan result rows into struct fields using pgx.RowToStructByName, and handle the pgx.ErrNoRows case by returning a domain ErrNotFound error.

Prompt 16: Create a Go database migration setup using golang-migrate. Define migration files as sequential SQL up and down files, run migrations automatically on startup in development and as a separate CLI command in production, log each migration applied, and show how to roll back the last migration. Prompt 17: Write a Go repository layer using sqlx. Define a ProductRepository that executes SELECT queries into struct slices using sqlx.Select, handles single row queries with sqlx.Get, uses named query placeholders :field for inserts and updates, and wraps multiple operations in a database transaction.

  • Prompt 18: Create a Go goroutine worker pool. Define a Pool with a configurable number of workers, a Job type with an execute function, and a Results channel. Show how to submit jobs without blocking when the queue is full, collect results, and shut down the pool gracefully when all jobs are complete.
  • Prompt 19: Write a Go fan-out pattern that dispatches a slice of work items to N goroutines, collects all results via a channel, and returns the aggregated results preserving order. Handle partial errors by including both results and errors in the output type.
  • Prompt 20: Create a Go rate limiter using a token bucket algorithm. Define a Limiter struct that allows N requests per second per key, stores buckets in a sync.Map, refills tokens in a background goroutine, and exposes an Allow(key string) bool method safe for concurrent use.
  • Prompt 21: Write a Go in-memory cache using sync.Map with TTL expiry. Define a Cache[K, V] generic struct, an expiring entry type, a Set method that stores the value with an expiry time, a Get method that returns the value if not expired, and a background goroutine that evicts expired entries every 60 seconds.
  • Prompt 22: Create a Go context propagation pattern. Show how to store a request ID in context.Context using a typed key, how a logger reads the request ID from context and adds it to every log line, and how a downstream HTTP client reads the request ID from context and adds it to outgoing request headers.
  • Prompt 23: Write a Go gRPC server for a UserService. Define the Protobuf service with GetUser, CreateUser, and ListUsers RPCs. Implement the service interface in Go, add a gRPC middleware that validates JWT tokens and injects the user claim into context, and show the server startup code with reflection enabled for grpcui.
  • Prompt 24: Create a Go gRPC client with connection pooling and retry. Connect to a gRPC server with TLS, add a retry interceptor that retries on Unavailable and DeadlineExceeded status codes with exponential backoff, and show how to call GetUser and handle the gRPC status error codes.
  • Prompt 25: Write a Go event-driven pattern using channels. Define an EventBus with a Publish method and a Subscribe method that returns a channel. Show how multiple subscribers receive the same event, how to unsubscribe, and how to prevent a slow subscriber from blocking the publisher using a buffered channel with a non-blocking send.
  • Prompt 26: Create a Go unit test for a service function. Mock the repository interface using a hand-written mock struct, test the happy path, test the error path when the repository returns an error, verify that the correct repository methods were called with the correct arguments using a call recorder, and use testify/assert for assertions.
  • Prompt 27: Write a Go integration test for a Gin HTTP handler using httptest. Create a test server with the handler registered, send a POST request with a JSON body, assert the response status code and body, seed the test database before the test and clean up after, and run the test with a real PostgreSQL instance via docker-compose.
  • Prompt 28: Create a Go table-driven test for a pure function. Define a slice of test cases with input and expected output, range over them in the test function, use t.Run with the test case name for sub-tests so each case appears separately in test output, and verify error cases return the expected error type.

FAQ

Should I use Gin or the standard library for a Go HTTP server?

Gin for most projects. Gin adds routing with path parameters, middleware chaining, JSON binding, and validation on top of net/http. The standard library ServeMux in Go 1.22+ now supports method-based routing and path parameters, reducing the gap. Use the standard library if you want zero dependencies and your routing needs are simple. Use Gin for REST APIs with middleware, complex routing, and JSON handling — it covers the common cases with less boilerplate.

How does Go handle concurrency differently from Node.js?

Go uses goroutines — lightweight OS threads managed by the Go runtime — which allow true parallel execution across multiple CPU cores. Node.js uses a single-threaded event loop with async/await for concurrency but not true parallelism (Worker Threads add parallelism but are more complex). Go goroutines are cheaper to create than OS threads and the Go scheduler multiplexes them efficiently. For CPU-bound work, Go is faster. For I/O-bound work, both are efficient. Channels are the idiomatic Go communication primitive; callbacks and Promises are the Node.js equivalent.

What is the best ORM for Go?

The Go community is divided on ORMs. GORM is the most popular but is criticised for performance overhead and magic behaviour. sqlx and pgx are popular alternatives that stay close to SQL while adding type-safe scanning. sqlc generates type-safe Go code from SQL queries — write SQL, get generated Go functions. Many experienced Go developers prefer sqlc or raw pgx for clarity and performance, and avoid ORMs entirely. For simple CRUD, GORM or ent work well and reduce boilerplate.

Is Go good for beginners?

Go is one of the better languages for developers coming from dynamic languages. The syntax is simple with few keywords, the toolchain is a single binary, the standard library covers most needs, and the compiler catches many errors at compile time. The main adjustment is explicit error handling (returning errors rather than throwing exceptions) and understanding pointers. Most developers are productive in Go within a few weeks.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.