ETag
ETag middleware for Fiber that helps caches validate responses and saves bandwidth by avoiding full retransmits when content is unchanged.
Signaturesβ
func New(config ...Config) fiber.Handler
func Generate(body []byte) []byte
func GenerateWeak(body []byte) []byte
Generate and GenerateWeak build the validator the middleware sets, quotes included ("13-1831710635" and W/"13-1831710635" for Hello, World!), from the body length and a CRC-32 checksum of the body, so a handler can compute one itself. Both return nil for a body longer than math.MaxUint32 bytes.
Examplesβ
Import the middleware package:
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/etag"
)
Once your Fiber app is initialized, use the middleware like this:
// Initialize default config
app.Use(etag.New())
// GET / -> ETag: "13-1831710635"
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
// Or extend your config for customization
app.Use(etag.New(etag.Config{
Weak: true,
}))
// GET / -> ETag: W/"13-1831710635"
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
The middleware sets an ETag only on a 200 response with a non-empty body. It skips the response, without comparing If-None-Match, when the handler already set an ETag (in any letter case) and for Server-Sent Events (text/event-stream) responses and other streams that declare no length, whose body it would otherwise have to buffer to its end. A stream of known length, such as SendFile serves, is read into memory to hash it, and one that ends early, fails or runs past that length is sent on without an ETag.
A matching If-None-Match yields 304 Not Modified only for GET and HEAD requests, the methods RFC 9110 defines it for. Other methods pass through unchanged, with the ETag header still set. They are not answered with 412 Precondition Failed: the middleware runs after the handler, over the response it produced, so the method has already been applied and the status whose purpose is to prevent that would misreport what happened.
Entity tags in requests must be quoted per RFC 9110. For example:
If-None-Match: "example-etag"
Configβ
| Property | Type | Description | Default |
|---|---|---|---|
| Weak | bool | Enables weak validators. Weak ETags are easier to generate but less reliable for comparisons. | false |
| Next | func(fiber.Ctx) bool | Next defines a function to skip this middleware when it returns true. | nil |
Default Configβ
var ConfigDefault = Config{
Next: nil,
Weak: false,
}