Building a Go Backend from Scratch with Claude Code
The previous posts covered pitfalls and mindset. This one ties them together with a complete Go backend workflow from scratch.
The stack is Go 1.22 + Gin + PostgreSQL + GORM, and the goal is to ship the initial core skeleton of an IoT device management backend: layered directory structure, data models, a Device CRUD API, JWT and logging middleware, and local integration testing (leaving complex domain logic like real-time push and alerting rule engines for later iterations instead of cramming them into the initial scaffold). Below is the step-by-step breakdown: the exact prompts I used, the key code, the pitfalls that required manual intervention, and the parts where Claude can’t help.
Step 0: Write CLAUDE.md
Before writing a single line of application code, I asked Claude to draft a CLAUDE.md, then edited it by hand.
A bad CLAUDE.md (too vague—Claude will keep asking clarifying questions):
1 | # Project |
A good CLAUDE.md (concrete and actionable):
1 | # Project Info |
The difference is simple: vague slogans like “write good code” do nothing, whereas concrete rules like “all API routes must go through the auth middleware” directly constrain Claude’s output. This CLAUDE.md took 10 minutes and saved repeated back-and-forth on every step that followed.
Step 1: Project Scaffolding
My prompt:
Initialize a Go backend project using Gin. Organize it into handler / service / repository / model layers. Create the
main.goentry point and the base directory structure.
Claude generated the full directory layout and config files:
1 | l4_cloud/ |
It generated the Makefile alongside it:
1 |
|
My adjustments: I kept the standard Go layout cmd/server/main.go (matching the Makefile above) and filled in the missing database connection string and JWT_SECRET placeholders in .env.example.
Time spent: 5 minutes (at least 30 minutes by hand)
Step 2: Data Models
My prompt:
Define these data models:
Device(withname,type, andstatusfields) andSensorData(withdevice_id,temperature,humidity, andtimestampfields). Follow idiomatic GORM conventions and the layered structure inCLAUDE.md.
The adjusted Device model:
1 | // internal/model/device.go |
Pitfall 1: Untyped Status field. Claude initially typed Status as a raw string—it compiles, but offers zero type safety. I refactored it into a custom DeviceStatus enum type with an IsValid() method so the service layer can validate status values and reject arbitrary strings.
Pitfall 2: Duplicate timestamp on SensorData. gorm.Model already embeds CreatedAt. Although SensorData conceptually tracks a collection timestamp, the extra Timestamp field Claude added overlapped semantically with CreatedAt, so I dropped Timestamp and reused gorm.Model‘s built-in timestamp instead:
1 | // internal/model/sensor_data.go |
Time spent: 10 minutes (including adjustments)
Step 3: CRUD API
My prompt:
Implement the full CRUD API for the
Devicemodel. Requirements:
- Follow the handler / service / repository layering
- Use a Gin route group with auth middleware (a placeholder middleware is fine for now)
- Return errors in a uniform format:
{ "code": 40001, "message": "xxx" }- Add unit tests with a mocked repository layer
Claude generated roughly 400 lines of cleanly layered code. Key snippets:
Handler layer (list endpoint):
1 | // internal/handler/device.go |
Uniform error format:
1 | // internal/errors/errors.go |
Fix 1: Don’t hardcode HTTP 400. The first draft of Respond() hardcoded http.StatusBadRequest, which caused ErrNotFound and ErrInternal to return HTTP 400 as well. Adding an unserialized HTTPStatus field (json:"-") to AppError maps each application error code to its proper HTTP status code.
Fix 2: Pagination defaults and bounds checks. Claude defaulted page to 0, which is counterintuitive for 1-indexed pagination and passes negative values straight through to the database query. I switched the default to 1 and added bounds clamping:
1 | page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) |
Unit test (mock repository—note the pagination bounds guard to prevent a slice panic when start > len(m.devices)):
1 | // internal/handler/device_test.go |
Time spent: 15 minutes (at least 2 hours by hand)
Step 4: Middleware
My prompt:
Write two middleware functions:
- Auth middleware: extract the Bearer token from the
Authorizationheader, verify the JWT, and inject user info into the context- Logger middleware: log each request’s method, path, latency, and status code
Match the existing codebase style.
The auth middleware Claude generated:
1 | // internal/middleware/auth.go |
Pitfall: Hardcoded JWT secret. Claude initially declared jwtSecret as a package-level constant. I changed it to an injected function parameter backed by a config struct loaded from environment variables:
1 | // config/config.go |
The logger middleware had no issues—Claude picked up the existing internal/logger package automatically and produced consistent output:
1 | // internal/middleware/logger.go |
Time spent: 10 minutes
Step 5: Integration Testing
Claude’s value drops here because you need a live server and a real database.
Start PostgreSQL:
1 | docker run -d --name l4-postgres \ |
Run unit tests:
1 | make test |
Smoke-test with curl:
1 | # Create a device |
Pitfall: JSON tag typo. On the first live test, the endpoint returned {"devie_id": 1} instead of device_id because the generated SensorData struct had a typo: `json:"devie_id"` (Step 2 above shows the fixed version). Typos like this slip right past visual review and show up immediately on a curl call.
Pitfall: Conflating missing records with database errors. When fetching a single device, blindly mapping every err != nil to HTTP 404 hides real database connection failures. Conversely, if a repository branch returns (nil, nil), serializing it directly causes subtle bugs. I updated the handler to distinguish gorm.ErrRecordNotFound from internal errors and guard against device == nil:
1 | device, err := h.service.GetByID(id) |
Time spent: 30 minutes
Time Breakdown
| Stage | Manual Estimate | With Claude Code | Time Saved |
|---|---|---|---|
| Project scaffolding | 30 min | 5 min | 83% |
| Data models | 20 min | 10 min | 50% |
| CRUD API | 2 h | 15 min | 87% |
| Middleware | 1 h | 10 min | 83% |
| Integration testing | 1 h | 30 min | 50% |
| Total | ~5 h | ~1 h 10 min | ~76% |
The biggest speedup came from the CRUD API—patterned, cleanly layered code that Claude gets right almost on the first try. Data modeling and integration testing saw the smallest gains because they require domain judgment and live verification.
Where Claude Can’t Help
Honestly, I still handle the following stages myself. Here is a simple heuristic for dividing the work:
Where Claude shines (clear patterns inferable from CLAUDE.md):
- Boilerplate and patterned code (CRUD endpoints, middleware, config loading)
- Project scaffolding and directory layout
- Unit tests and mock implementations
- Fixing known bugs (paste the error output and let it iterate)
Where Claude falls short (requires business context or live environment verification):
| Area | Why Claude Can’t Help | Your Move |
|---|---|---|
| Architecture design | Tech choices depend on traffic scale, team skills, and ops constraints | Make the call yourself; have Claude implement it |
| Business thresholds | It doesn’t know how long an offline device takes to trigger an alert | Define the rules; let Claude write the validation logic |
| Deployment config | Docker Compose and Nginx configs need verification against real infrastructure | Write and debug them yourself |
| Architectural code review | Spotting that “this service owns too many responsibilities” is a judgment call | Review it yourself—Claude won’t flag it |
A simple rule of thumb: If a decision depends on “how many devices we manage,” “expected QPS,” or “who owns which service,” Claude can’t make it. If it only depends on “which framework,” “how layers are split,” and “naming conventions,” a solid CLAUDE.md is all it needs.
Key Takeaways
1. CLAUDE.md is the highest-ROI 10 minutes you will spend. The more concrete your rules, the less friction you hit later. “Write good code” is noise; “handlers never call GORM directly” is an instruction Claude can follow.
2. Layered architecture pairs naturally with AI assistance. Clear boundaries make prompts trivial to write—“add a field to the model layer,” “handle pagination in the handler.” Give Claude spaghetti code and it will struggle just as much as a human.
3. Focus your review on business logic, not syntax. Claude rarely makes syntax errors, but edge cases (0-based vs. 1-based pagination, nil-pointer handling) are on you. Make “generate first, then verify with curl“ a reflex.





