Fiber Web Framework

repository·main·Indexed 12 days ago

https://github.com/gofiber/fiber

An Express-inspired web framework for Go built on top of Fasthttp, designed for high performance and low memory footprint. Fiber v3 introduces unified Binders for request and response binding, a fluent HTTP client, and a Retry addon with exponential backoff.

Tokens
196.6K
Snippets
603
Records
757
Agent score
98%

What's inside Fiber

  1. Features of the Fiber Client

    main

    The Fiber Client is an easy-to-use HTTP client based on fasthttp, inspired by Resty and Axios. Key capabilities include:

    • HTTP Methods: Supports GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
    • Fluent API: Provides simple and chainable methods for configuring requests and settings.
    • Flexible Request Bodies: Accepts string, []byte, map, or slice. It automatically detects Content-Type and supports buffer processing for files.
    • Low-level Access: You can access the native *fasthttp.Request instance during middleware and request execution via Request.RawRequest. The request body can be read multiple times using Request.RawRequest.GetBody().
    • Rich Responses: Access response data as []byte using response.Body() or as a string using response.String().
    • Automatic Marshalling:
      • Automatically marshals/unmarshals JSON and XML content types.
      • Defaults to JSON if a struct/map is provided without a Content-Type header.
      • Supports automatic unmarshalling for success scenarios via Request.SetResult() / Response.Result() and error scenarios via Request.SetError() / Response.Error().
      • Supports RFC7807 (application/problem+json & application/problem+xml).
      • Allows overriding JSON and XML Marshaller/Unmarshaller via options.
  2. Encrypt Cookie middleware

    main

    The encryptcookie middleware encrypts cookie values for secure storage. It encrypts the cookie values themselves, but not the cookie names.

    To use it, register the middleware using encryptcookie.New() with a configuration object containing a Key.

    import (
        "github.com/gofiber/fiber/v3"
        "github.com/gofiber/fiber/v3/middleware/encryptcookie"
    )
    
    // ...
    
    app.Use(encryptcookie.New(encryptcookie.Config{
        Key: "secret-32-character-string",
    }))
  3. Performance Benchmarks via TechEmpower

    main
    Fiber's performance is validated through TechEmpower benchmarks, which compare web frameworks across fundamental tasks like JSON serialization, database access, and server-side template rendering. These benchmarks run under realistic production configurations on high-performance hardware (e.g., 56-core Intel Xeon, 64GB RAM, Enterprise SSD) to provide a meaningful comparison against other frameworks like Express.
  4. Use the Adaptor package for Fiber and net/http interop

    main

    The adaptor package allows you to reuse handlers, middleware, and requests across Fiber and the standard net/http library.

    Key Capabilities:

    • Convert net/http handlers/middleware to Fiber.
    • Convert Fiber handlers/apps to net/http.
    • Convert fiber.Ctx to *http.Request.
    • Propagate context.Context values between frameworks.

    Important Considerations:

    • Performance: Adapted net/http handlers run with standard library semantics and do not have access to fiber.Ctx. They incur more overhead than native Fiber handlers. Use them for interop or legacy support, but prefer native Fiber handlers for performance-critical paths.
    • Body Limits: When running a Fiber app inside net/http (via FiberHandler, FiberHandlerFunc, or FiberApp), the adaptor enforces the Fiber app's configured BodyLimit. The default is 4 MiB. Requests exceeding this limit will receive a 413 Request Entity Too Large error.
  5. Use Fiber Binders for request/response binding

    main

    Introduced in Fiber v3, Binder is the unified feature for request and response binding. It replaces older components like BodyParser, QueryParser, ParamsParser, and others. Binders allow you to map incoming request data (from JSON, XML, Forms, Query params, etc.) directly into Go structs or maps.

    Available default binders include:

    • Form
    • Query
    • URI
    • Header
    • Response Header
    • Cookie
    • JSON
    • XML
    • CBOR
  6. What is State Management in Fiber

    main

    State management provides a global key–value store for application dependencies and runtime data. This store is shared across the entire application and persists between requests. It is commonly used to store Services, which can be retrieved using GetService or MustGetService.

    Important Considerations

    • Prefork Mode: When prefork is enabled, each worker process has its own independent state store. State is not shared between workers by default.
    • Concurrency: The State type is built on top of sync.Map, ensuring thread-safe access for concurrent requests.
  7. How validation works in Fiber

    main

    Fiber does not include a built-in validation library to remain dependency-free. Instead, it uses a pluggable architecture via the StructValidator field in fiber.Config.

    When you provide an implementation of the Validate(out any) error method to StructValidator, Fiber's Bind methods (such as Body, Query, Form, etc.) will automatically trigger that validator whenever data is being bound onto a struct or a pointer to a struct.

    Important Note: Validation only runs for struct destinations. Binding data into maps or other non-struct types will skip the validation step.

    app := fiber.New(fiber.Config{
        StructValidator: &myValidator{},
    })
    
    // In a handler:
    if err := c.Bind().Body(userStruct); err != nil {
        // err will contain validation errors if the struct tags fail
        return err
    }
  8. Understand default cache key behavior

    main

    To prevent collisions while keeping fragmentation bounded, the default cache key includes:

    • Request method
    • Request path
    • Canonicalized query string (unless DisableQueryKeys is true)
    • Representation-driving request headers: accept, accept-encoding, and accept-language.

    Important: The default key does not include the request body or form values. If you enable caching for methods that carry a body (like QUERY via the Methods config), you must provide a custom KeyGenerator that incorporates c.Request().Body() to avoid collisions.

  9. Identify responses that are never stored

    main

    The middleware skips caching (returning X-Cache: unreachable) for responses that are personalized for a specific client. These include:

    • Responses that set a cookie: Any response with a Set-Cookie header is considered per-client.
    • Responses with Authorization: Unless the response explicitly permits shared caching.
    • Specific Cache-Control directives: no-store, private, no-cache, or Vary: *.

    Note on Cookies: If your application refreshes a session cookie on every response, those routes will not be cached. To allow caching for routes that might otherwise be considered private, use Cache-Control: public or s-maxage.

  10. Use Express-style request handlers

    main

    Fiber supports Express-style signatures using fiber.Req and fiber.Res helpers. This is useful for developers coming from Node.js/Express or for writing middleware that follows that pattern.

    Key Behaviors:

    • Next Callback: If your signature includes a next function, Fiber injects it. Calling next() continues the chain; not calling it stops the chain.
    • Error Handling: If you use a next callback that accepts an error (e.g., func(error)), calling next(err) short-circuits the chain with that error. If the handler itself returns an error, Fiber prioritizes the handler's return value over the error passed to next.
    • Limitations: Fiber does not support the Express four-argument error handler (func(err, req, res, next)). Instead, non-nil errors are sent to the app's central ErrorHandler.
    // Example of an Express-style middleware
    app.Use(func(req fiber.Req, res fiber.Res, next func() error) error {
        if req.IP() == "192.168.1.254" {
            return res.SendStatus(fiber.StatusForbidden)
        }
        return next()
    })
    
    // Example of an Express-style route
    app.Get("/express", func(req fiber.Req, res fiber.Res) error {
        return res.SendString("Hello from Express-style handlers!")
    })
  11. Choose between Infrastructure-level and Application-level CORS

    main

    When deploying Fiber applications, you must decide where to handle CORS.

    Handle CORS at the edge using CDNs (CloudFront, CloudFlare), API Gateways (AWS, Google Cloud), Load Balancers, or Reverse Proxies (Nginx, Apache). Advantages: Better performance, reduced server load, and centralized configuration. Requirement: If using this, disable Fiber's CORS middleware to avoid conflicts.

    Option 2: Application-level CORS (Fiber Middleware)

    Use Fiber's middleware when you need:

    • Dynamic origin validation based on application logic.
    • Fine-grained control over CORS policies per route.
    • Integration with application state (e.g., database-driven origins).
    • Development environments where infrastructure CORS is unavailable. Requirement: Ensure all CORS headers reach Fiber unchanged by your infrastructure.
  12. How CORS middleware works in Fiber

    main

    The CORS middleware manages Cross-Origin Resource Sharing by adding appropriate headers to responses. It handles two types of requests:

    1. Preflight Requests: These are HTTP OPTIONS requests sent by browsers to check if a cross-origin request is safe. The middleware intercepts these, responds with the configured CORS headers, and ends the request cycle.
    2. Actual Requests: For non-preflight requests, the middleware adds the configured CORS headers to the response and passes the request to the next handler.

    To ensure caches store the correct responses, the middleware automatically sets the Vary header (e.g., Vary: Origin) so that different origins receive the correct headers from cached content.