golid / rules
Cursor rule40 starsChanged 6 months agoMITView on GitHub
Patterns for Go handler layer files — HTTP request handling, validation, routing
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- .cursor/rules/audit-bugs.mdcCursor rule
- .cursor/rules/audit-codebase.mdcCursor rule
- .cursor/rules/ci-workflow.mdcCursor rule
- .cursor/rules/codebase-standards.mdcCursor rule
- .cursor/rules/common-commands.mdcCursor rule
- .cursor/rules/deploy-infra.mdcCursor rule
- .cursor/rules/document-module.mdcCursor rule
- .cursor/rules/dynamic-image-endpoints.mdcCursor rule
- .cursor/rules/dynamic-image-http.mdcCursor rule
- .cursor/rules/external-api.mdcCursor rule
- .cursor/rules/feature-flags.mdcCursor rule
- .cursor/rules/frontend-components-advanced.mdcCursor rule
- .cursor/rules/frontend-components.mdcCursor rule
- .cursor/rules/frontend-forms.mdcCursor rule
- .cursor/rules/frontend-lib.mdcCursor rule
- .cursor/rules/git-commits.mdcCursor rule
- .cursor/rules/go-service-errors.mdcCursor rule
- .cursor/rules/go-service.mdcCursor rule
- .cursor/rules/iteration-surface.mdcCursor rule
- .cursor/rules/job-queue.mdcCursor rule
- .cursor/rules/observability.mdcCursor rule
- .cursor/rules/openapi.mdcCursor rule
- .cursor/rules/parallel-subagents.mdcCursor rule
- .cursor/rules/plan-execution-loop.mdcCursor rule
- .cursor/rules/plan-feature-execution.mdcCursor rule
- .cursor/rules/plan-feature.mdcCursor rule
- .cursor/rules/plan-infra.mdcCursor rule
- .cursor/rules/planning-standards.mdcCursor rule
- .cursor/rules/refactor-large-files.mdcCursor rule
- .cursor/rules/rename-tool.mdcCursor rule
- .cursor/rules/seed-data.mdcCursor rule
- .cursor/rules/slice-and-ship.mdcCursor rule
- .cursor/rules/solidjs-data-fetching.mdcCursor rule
- .cursor/rules/solidjs-pages.mdcCursor rule
- .cursor/rules/solidstart-routing.mdcCursor rule
- .cursor/rules/sql-migrations.mdcCursor rule
- .cursor/rules/sse-realtime.mdcCursor rule
- .cursor/rules/workflow-routing.mdcCursor rule
- .cursor/rules/write-rules.mdcCursor rule
- .cursor/rules/write-tests-e2e.mdcCursor rule
- .cursor/rules/write-tests-frontend.mdcCursor rule
- .cursor/rules/write-tests-frontend-workflow.mdcCursor rule
- .cursor/rules/write-tests.mdcCursor rule
- .cursor/rules/write-tests-planning.mdcCursor rule
The file
We split this go-handler.mdc into the rules it gives an agent
4 rules. About 0 are common, 2 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 27
No business logic in handlers.
- Distinctive: line 44
Every protected handler starts with:
- Very specific: line 97
Always use apperror — never echo.NewHTTPError:
- Very specific: line 133
Always validate query params.
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: Patterns for Go handler layer files — HTTP request handling, validation, routing
globs: backend/internal/handler/*.go,backend/internal/handler/**/*.go,backend/internal/middleware/*.go,backend/internal/middleware/**/*.go
alwaysApply: false
---
# Go Handler Layer Patterns
> **Thesis:** Handlers are thin translators between HTTP and services. They validate input, extract auth, delegate to services, and return JSON — nothing more.
>
> **Refrain:** `Extract → Validate → Delegate → Return`
**Reference files:** `auth.go`, `user.go`, `middleware/stack.go`
**Before modifying a module's handler** (changes to validation, auth, or route
registration), read `docs/modules/{module}/spec.md` for API surface and
validation rules. For cross-module request chains, also check `docs/flows.md`.
## Structure
```go
type XHandler struct { xService xServicer }
func NewXHandler(xService *service.XService) *XHandler { ... }
```
- Handlers are thin — validate input, delegate to service, return JSON.
- No business logic in handlers. No direct DB access.
- **Struct field is the interface** (`xServicer`), constructor takes the concrete type. This is the standard pattern — `make new-module` generates it automatically.
## Service Interfaces
Handlers use unexported interfaces (`authServicer`, `userServicer`, `sseHubber`), not concrete service types. This enables mock-based testing. Constructor takes concrete types (callers unchanged), struct field is the interface. See `handler/interfaces.go`.
## Scaffold Output
`make new-module name=items` generates:
- `handler/item.go` — Handler with interface-typed service field
- `handler/item_test.go` — Mock struct + 5 test stubs (Create success, Create validation, List, GetByID not found, Delete)
- Interface entry appended to `handler/interfaces.go`
- Fill in test bodies for your specific validation logic and error paths.
## Auth Extraction
Every protected handler starts with:
```go
userID, err := requireUserID(c)
if err != nil { return err }
userType, err := requireUserType(c)
if err != nil { return err }
```
Role guards (when needed) go after extraction:
```go
if userType != "admin" {
return apperror.Forbidden("Only admins can create items")
}
```
Resource-level authorization is handled by the service layer, not the handler.
## Request Binding
```go
var req CreateXRequest
if err := c.Bind(&req); err != nil {
return apperror.BadRequest("Invalid request body")
}
```
Define request structs with `json` tags in the same handler file.
## Validation
Simple validations in the handler (required fields). Complex validations in a `validateX` function:
```go
func validateCreateItem(req *CreateItemRequest) error {
details := make(map[string]string)
if req.Title == "" { details["title"] = "Title is required" }
if len(details) > 0 {
return apperror.Validation("Validation failed", details)
}
return nil
}
```
## Response Codes
- `201 Created` for POST that creates a resource
- `200 OK` for GET, PUT, POST actions (publish, approve, etc.)
- `200 OK` with `{"message": "..."}` for DELETE
## Error Responses
Always use `apperror` — never `echo.NewHTTPError`:
```go
// BAD
return echo.NewHTTPError(http.StatusForbidden, "not allowed")
// GOOD
return apperror.Forbidden("not allowed")
```
## Route Registration
Wire new modules through `internal/wire/` — not `main.go`. `main.go` only calls `wire.BuildServices`, `wire.BuildHandlers`, and `wire.RegisterRoutes`.
1. **`wire/services.go` (`BuildServices`)** — construct the service from its subpackage:
```go
xService := x.NewXService(pool, cfg.PaginationDefault, cfg.PaginationMax)
// Add field to Services struct: X *x.XService
```
2. **`wire/handlers.go` (`BuildHandlers`)** — construct the handler (constructor takes concrete subpackage types):
```go
X: handler.NewXHandler(svcs.X, cfg.PaginationDefault, cfg.PaginationMax),
```
3. **`wire/routes.go`** — register routes on the appropriate group (`registerProtectedRoutes`, `registerAdminRoutes`, etc.):
```go
protected.POST("/x", h.X.Create)
protected.GET("/x", h.X.List)
protected.GET("/x/:id", h.X.GetByID)
```
## Query Parameter Parsing
Always validate query params. Never ignore `strconv` errors:
```go
// BAD — silent invalid page
page, _ := strconv.Atoi(c.QueryParam("page"))
// GOOD — default on error
page, err := strconv.Atoi(c.QueryParam("page"))
if err != nil || page < 1 { page = 1 }
perPage, err := strconv.Atoi(c.QueryParam("per_page"))
if err != nil || perPage < 1 || perPage > 100 { perPage = 20 }
```
For enum-like string params, validate against allowed values:
```go
status := c.QueryParam("status")
if status != "" && status != "active" && status != "completed" {
return apperror.BadRequest("Invalid status filter")
}
```
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

