Idempotence

The idempotence middleware of Fiber allows for the creation of fault-tolerant APIs, where repeated requests (e.g., due to client network issues) do not erroneously cause the same operation to be executed multiple times on the server, serving as a general API idempotence mechanism.

Function Signature

func New(config ...Config) fiber.Handler

Example Code

Import the middleware package of the Fiber web framework.

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/idempotency"
)

Default Configuration

After initializing the Fiber application, the middleware can be directly referenced.

app.Use(idempotency.New())

Custom Configuration

app.Use(idempotency.New(idempotency.Config{
    Lifetime: 42 * time.Minute,
    // ...
}))

Configuration Options

Property Type Description Default Value
Next func(*fiber.Ctx) bool Next defines a function to skip the middleware when it returns true. A function for safe method usage
Lifetime time.Duration Lifetime is the maximum lifespan of the idempotence key. 30 * time.Minute
KeyHeader string KeyHeader is the name of the header containing the idempotence key. "X-Idempotency-Key"
KeyHeaderValidate func(string) error KeyHeaderValidate defines a function for validating the syntax of the idempotence header. A function for UUID validation
KeepResponseHeaders []string KeepResponseHeaders is the list of headers to be preserved from the original response. nil (preserves all headers)
Lock Locker Lock locks the idempotence key. A lock in memory
Storage fiber.Storage Storage stores the response data according to the idempotence key. Storage in memory

Default Configuration

var ConfigDefault = Config{
    Next: func(c *fiber.Ctx) bool {
        // Skip the middleware if the request is made using safe HTTP methods
        return fiber.IsMethodSafe(c.Method())
    },
    Lifetime: 30 * time.Minute,
    KeyHeader: "X-Idempotency-Key",
    KeyHeaderValidate: func(k string) error {
        if l, wl := len(k), 36; l != wl { // UUID length is 36 characters
            return fmt.Errorf("%w: invalid length: %d != %d", ErrInvalidIdempotencyKey, l, wl)
        }
        return nil
    },
    KeepResponseHeaders: nil,
    Lock: nil, // Set in configDefault to avoid data allocation here
    Storage: nil, // Set in configDefault to avoid data allocation here
}