Skip to main content

Write Your Own Middleware

ยท 5 min read
Fiber Team
Maintainers

You use logger, cors, and limiter every day. Sooner or later you need something Fiber does not ship: tenant resolution from the hostname, an audit trail, a company-specific auth header. The instinct is to look for a plugin API or an interface to implement.

There is none, and that is the point. A Fiber middleware is an ordinary handler - func(c fiber.Ctx) error - that calls c.Next() to hand control to the rest of the chain. Everything else, including the polished config pattern the official middleware uses, is convention on top of that one idea.

This post walks through the whole ladder: the minimal middleware, short-circuiting, passing data downstream, and the official Config convention, ending with the one caveat that catches almost everyone.

Route Constraints: Validation Before Your Handler Runs

ยท 5 min read
Fiber Team
Maintainers

Almost every REST API has a handler that starts like this:

app.Get("/users/:id", func(c fiber.Ctx) error {
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return fiber.ErrBadRequest
}
// ... finally, the actual logic
})

Three lines of ceremony before the handler does anything useful, repeated in every handler that takes a numeric parameter. Fiber has a feature that moves this check into the router itself: route constraints. Declare the parameter as :id<int> and the route simply does not match for /users/abc. Your handler only ever sees values that passed the check.

Constraints arrived back in v2.37 and were inspired by .NET Core routing. They remain one of the least-known routing features, which is a shame, because they remove boilerplate exactly where it accumulates fastest.

The Fiber CLI

ยท 4 min read
Fiber Team
Maintainers

Most Go web frameworks give you a library and send you on your way. Fiber ships a CLI tool that handles the repetitive tasks around development: live reload when files change, project scaffolding from templates, serving static files with one command, and migrating between Fiber versions automatically.

You do not need the CLI to use Fiber. But once you try fiber dev instead of manually restarting your server after every change, you will not go back.