package etag import ( "encoding/hex" "hash/fnv" "net/http" ) // Generator is a function that will be used to generate ETag values based on the response body. // The returned string must consist of etagc only (visible ASCII except `"`, plus non-ASCII bytes). type Generator func([]byte) string // Skipper is a function that can be used to skip ETag processing for certain requests. type Skipper func(*http.Request) bool // defaultMaxBufferSize is the default upper limit of the response body buffer size (1 MiB). const defaultMaxBufferSize = 1 << 20 type config struct { generator Generator maxBufferSize int skipper Skipper weak bool } var defaultConfig = config{ generator: func(b []byte) string { h := fnv.New64a() h.Write(b) return hex.EncodeToString(h.Sum(nil)) }, maxBufferSize: defaultMaxBufferSize, skipper: func(_ *http.Request) bool { return false }, weak: true, } // Option is a function to configure the ETag middleware. type Option func(*config) // WithGenerator allows you to provide a custom ETag generator function, which will be used to generate ETag values // based on the response body. If not provided, a default generator (FNV-1a hash) will be used. func WithGenerator(generator Generator) Option { return func(cfg *config) { cfg.generator = generator } } // WithSkipper allows you to provide a custom Skipper function, which can be used to skip ETag processing for certain requests. // The default Skipper function does not skip any requests. // // Regardless of the Skipper function, ETag processing will be skipped for streamed responses and // for responses with status codes other than 200 OK, 201 Created. // If you need to add ETags to these responses, do it manually in your handler. func WithSkipper(skipper Skipper) Option { return func(cfg *config) { cfg.skipper = skipper } } // WithWeak allows you to specify whether the generated ETag should be treated as weak or strong. // The default value is true, meaning that the generated ETag will be prefixed with "W/" // // The reason for this default behavior is that response body representation might change by compression or other transformations. // If you are sure that response body representation will not change and you need strong ETags (e.g., for If-Match header), // you can set this option to false. func WithWeak(weak bool) Option { return func(cfg *config) { cfg.weak = weak } } // WithMaxBufferSize allows you to specify the maximum size of the response body buffer in bytes. // The default value is 1 MiB. // // The middleware buffers the entire response body to generate an ETag. // If the body exceeds this limit, the middleware stops buffering and sends the response without generating ETag. // // size must be positive. Behavior for zero or negative values is undefined; do not rely on it. func WithMaxBufferSize(size int) Option { return func(cfg *config) { cfg.maxBufferSize = size } }