# Add Input Validation to a Fiber API

Yes. An agent wires go-playground/validator into Fiber v3's StructValidator, binds the create handler into a tagged struct, answers 400 with field errors, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-input-validation/fiber/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads what the handlers accept before it adds a rule, because in Fiber v3 validation is a one-time setting on the app that only pays off if the handlers bind into structs. In a project like gofiber/boilerplate, `handlers/handlers.go` has three handlers: `UserList` returns `{"success": true, "users": [...]}` from `database.Get()`, `UserCreate` builds `&models.User{Name: utils.CopyString(c.FormValue("user"))}` and calls `database.Insert` with no check at all, and `NotFound` serves `static/private/404.html`. `models/user.go` is a `User` struct with one `Name` field tagged `json:"name"`, and `database/database.go` is a slice behind a `sync.Mutex`. `app.go` builds `fiber.New(fiber.Config{})` with no `StructValidator`, adds `recover.New()` and `logger.New()`, and mounts the two handlers under `/api/v1`. `go.mod` is on `github.com/gofiber/fiber/v3` v3.6.1 and Go 1.26 with no validation library. The front end in `static/public/js/app.js` posts a `FormData` with a `user` field and skips the request when the input is empty, so the only guard is in the browser: an empty form field, a name of ten thousand characters or a JSON body with no `user` key all create a user, the last one with an empty name because `FormValue` reads form fields only.

Fiber does not bundle a validator; it runs whatever implements `Validate(out any) error` and is set as `fiber.Config.StructValidator`, every time a `Bind()` method fills a struct. The agent runs `go get github.com/go-playground/validator/v10`, the library the Fiber guide uses, adds a small adapter type wrapping `validator.New()` in a new `validation` package, and sets it in `fiber.Config` in `app.go`. It defines `CreateUserRequest` with `Name string` tagged `json:"user" form:"user" validate:"required,min=1,max=64"`, so the same struct binds a form post from the existing front end and a JSON body from an API client, and rewrites `UserCreate` to call `c.Bind().Body(&req)`, which picks the parser from the request's `Content-Type` and then runs the validator. `required` passes on a string of spaces, so the adapter also registers the `notblank` rule from the library's `non-standard/validators` package and the tag becomes `required,notblank,max=64`. `utils.CopyString` stays on the way into `models.User`, because fasthttp reuses request buffers after the handler returns.

A validation error is not a `fiber.BindError`: the guide is explicit that bind errors and validator errors are distinct, and a bare `error` returned from a handler reaches the default error handler as a 500. The agent sets a custom `ErrorHandler` in `fiber.Config` rather than unpacking errors in each handler, so every future handler that binds gets the same answer for free. It uses `errors.As` for `validator.ValidationErrors` and answers 400 with `{"success": false, "errors": [{"field": "user", "rule": "required"}]}`, taking the field name from the struct's `form` tag so clients see the name they sent; a `*fiber.BindError`, a body that is not valid JSON or form data, also answers 400 with the parse message; any other error falls through to `fiber.DefaultErrorHandler`. The `success` key matches the shape the existing handlers already return, and `app.js` is updated to show the first error message under the input instead of inserting a blank list item.

The tests are new, since the module has none. `handlers/handlers_test.go` builds the app through a `newApp()` constructor the agent extracts from `main`, and drives it with `app.Test`: a form post `user=Ada` answers 200 with the user; an empty `user` answers 400 with `field: user, rule: notblank`; a 65-character name answers 400 with `rule: max`; a JSON body `{"user": "Ada"}` with `Content-Type: application/json` answers 200, which proves one struct serves both clients; and a body of `{not json` answers 400 through the bind error branch rather than 500. A test on the adapter checks that the `notblank` rule is registered. The agent runs `go vet ./...`, `go test ./... -v -race` as `.github/workflows/test.yml` does, and `golangci-lint run` with the repository's `.golangci.yml`, then starts the server, posts a valid and an empty form with curl, and pastes both responses into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "codex",
  "input": "Add request validation to this Fiber v3 API. Read go.mod, app.go, handlers/handlers.go, models/user.go, database/database.go, static/public/js/app.js, static/public/index.html and the workflows under .github/workflows first. Add github.com/go-playground/validator/v10, wrap it in a type that implements Fiber's StructValidator interface and register the notblank rule from its non-standard validators, and set it in fiber.Config. Define a request struct for creating a user with json and form tags on the user field and validate tags for required, notblank and a maximum length, and rewrite the create handler to use c.Bind().Body so both form posts and JSON bodies are parsed and validated. Add a custom ErrorHandler that answers validator.ValidationErrors with 400 and a JSON list of field and rule using the form tag names, answers a fiber.BindError with 400, and defers everything else to the default handler. Keep utils.CopyString on the way into the model. Update app.js to show the first validation message. Extract a newApp constructor and write tests with app.Test for a valid form post, an empty name, an over-long name, a valid JSON body and a malformed body. Run go vet, go test -race and golangci-lint, start the server and curl a valid and an invalid post, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `app.go`, `handlers/handlers.go`, `go.mod`, `go.sum` and `static/public/js/app.js`, and adds a `validation` package and `handlers/handlers_test.go`. The description shows the two curl responses from the sandbox, a 200 with the created user and a 400 with `errors` naming the `user` field and the failed rule, and the `go test -race` output listing the new cases.

The run's record keeps `go vet`, the race run, the lint run and both posts, so a reviewer can see that a malformed body answers 400 and not 500, which is the branch the guide warns about.

Before merging, a reviewer decides whether the error messages should be translated through the library's `universal-translator`, whether a maximum length of 64 fits the product, and whether `UserList` should gain query validation for a future `limit` parameter through `c.Bind().Query`. The in-memory store and the static page markup are unchanged.

## Run it on every endpoint that accepts input unchecked

A team with several Fiber services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than a second pull request. Each run reads that service's own handlers and binds the ones that read `c.FormValue` or `c.Body` directly, and each opens its own pull request.

After that, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a handler that reads request data without c.Bind, or adds a request struct without validate tags, comment with the handler and the tags it should carry" reviews every later change. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

Validation added handler by handler drifts: one endpoint checks length, the next forgets, and the error shapes differ. Fiber v3's `StructValidator` makes it a property of the app, but only if someone wires the adapter, moves the handlers onto `Bind`, and handles the error type that would otherwise surface as a 500. The agent does the three together and writes the malformed-body case as a test, which is the one most often missed.

On Rush the race run, the lint and the live posts happen in the run's own sandbox with their output kept, so the pull request carries the 400 response it describes. A team with several Go services can run one of these per repository and review each pull request on its own.

## Frequently asked questions

### Why set a StructValidator instead of checking fields in the handler?

Because Fiber runs the configured validator on every `Bind().Body`, `Query`, `Form` and other bind call for a struct destination, so each new handler gets validation by writing tags rather than code. Per-handler checks work for one endpoint and drift across ten; the app-level setting keeps the rules beside the fields they describe.

### What does a client get back on bad input?

A 400 with `{"success": false, "errors": [{"field": "user", "rule": "notblank"}]}`, one entry per failed rule, using the field names from the `form` tags so they match what the client sent. A body that cannot be parsed at all also answers 400 with the parser's message. Without the custom error handler, a validation error returned from a handler is a plain `error` and Fiber answers 500, which is what the pull request fixes.

### Does one struct really serve both the form and JSON clients?

Yes. `c.Bind().Body` reads the request's `Content-Type` and parses a form post or a JSON body into the same struct, using the `form` and `json` tags respectively, and the validator runs once on the result. The existing front end keeps posting `FormData` unchanged, and an API client can send JSON, which the tests cover with one case each.

### Why the notblank rule?

The library's `required` rule fails on the zero value, which for a string is the empty string, so a name made of spaces passes it. `notblank`, from the library's `non-standard/validators` package, trims and then checks, which is what a name field means. The adapter registers it once when the validator is built.

## More Fiber jobs

- [Add JWT Authentication to a Fiber API](https://getrush.ai/run/add-jwt-authentication/fiber/)
- [Run a Fiber Docker Image as a Non-Root User](https://getrush.ai/run/add-non-root-user/fiber/)
- [Add OpenAPI Docs to a Fiber App](https://getrush.ai/run/add-openapi-docs/fiber/)

## The same job on other stacks

- [Add Input Validation to Firebase Cloud Functions](https://getrush.ai/run/add-input-validation/firebase-functions/)
- [Add Input Validation to a Hono API](https://getrush.ai/run/add-input-validation/hono/)
- [Add Input Validation to a Koa App](https://getrush.ai/run/add-input-validation/koa/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
