agentleFS
golid-aigolid-ai/golid/.cursor/rules/go-handler.mdc

golid / rules

Cursor rule40 starsChanged 6 months agoMITView on GitHub

Patterns for Go handler layer files — HTTP request handling, validation, routing

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
  1. Distinctive:

    No business logic in handlers.

    line 27
  2. Distinctive:

    Every protected handler starts with:

    line 44
  3. Very specific:

    Always use apperror — never echo.NewHTTPError:

    line 97
  4. Very specific:

    Always validate query params.

    line 133

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
go-handler.mdc
---
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")
}
```

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.