Fiber
02 / 02

Middleware, fasthttp Gotchas & Performance

Middleware, fasthttp Gotchas & Performance

Built-in Middleware

app := fiber.New()
app.Use(logger.New())
app.Use(recover.New())   // panic -> 500 instead of crashing the process
app.Use(cors.New())

// per-route: pass middleware before the final handler
app.Get("/admin", authMiddleware, adminHandler)

The fasthttp Ctx Reuse Gotcha

// WRONG — fasthttp reuses request buffers across requests for performance;
// this byte slice can be overwritten once the handler returns
func bad(c *fiber.Ctx) error {
  body := c.Body()
  go processLater(body)  // body may be mutated/reused by the time this runs
  return c.SendStatus(fiber.StatusOK)
}

// RIGHT — copy before the data needs to outlive the handler
func good(c *fiber.Ctx) error {
  body := append([]byte(nil), c.Body()...)
  go processLater(body)
  return c.SendStatus(fiber.StatusOK)
}

This is one of the most important Fiber-specific gotchas — forgetting to copy data before it outlives the handler can cause subtle, hard-to-debug corruption.

net/http Ecosystem Compatibility

Because Fiber isn't built on net/http, it generally isn't directly compatible with net/http-based middleware/libraries without an adapter — unlike Echo/Gin. Weigh this against fasthttp's throughput/allocation advantages when the HTTP layer itself is a measured bottleneck.

Static Files & Errors

app.Static("/static", "./assets")

app.Get("/users/:id", func(c *fiber.Ctx) error {
  user, err := findUser(c.Params("id"))
  if err != nil {
    return fiber.NewError(fiber.StatusNotFound, "user not found")
  }
  return c.JSON(user)
})

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free