@ fastify/ etag
用于 快捷化 自动生成 HTTP ETags 的 RFC2616-sec13 (英语)。 。 。 .
插件可以在ETag匹配如果-无匹配头时可选择发送304状态代码.
安装
npm i @fastify/etag
兼容性
| 插件版本 | 快速化版本 |
|---|---|
>=6.x | ^5.x |
>=4.x <6.x | ^4.x |
^3.x | ^3.x |
>=1.x <3.x | ^2.x |
请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 快速化 LTS 政策 更多细节.
示例
'use strict'
const Fastify = require('fastify')
const Etag = require('@fastify/etag')
const app = Fastify()
app.register(Etag)
app.get('/', async (req, reply) => {
return { hello: 'world' }
})
app.get('/manual-etag', async (req, reply) => {
// This will disable automatic ETag generation
// It will still return a 304 if the ETag matches
reply.header('etag', '"foobar"')
return 'world'
})
app.listen(3000)
插件选项
algorithm: 所有散列算法 :crypto模块支持。 默认 :'sha1'. (中文(简体) )'fnv1a'已贬值; 使用hashFn: Etag.fnv1a改为. )hashFn: 用于生成ETags的函数(称为string或者说Buffer有效载荷;返回未引用的散列。 提供时,algorithm选项将被忽略。 默认 :undefined。 。 。 .weak:默认生成弱ETags. 默认 :false。 。 。 .
使用自定义散列函数
'use strict'
const Fastify = require('fastify')
const Etag = require('@fastify/etag')
const app = Fastify()
app.register(Etag, {
hashFn: Etag.fnv1a // Use fnv1a provided by @fastify/etag
})
app.get('/', async (req, reply) => {
return { hello: 'world' }
})
app.get('/manual-etag', async (req, reply) => {
// This will disable automatic ETag generation
// It will still return a 304 if the ETag matches
reply.header('etag', '"foobar"')
return 'world'
})
app.listen(3000)
自动 304 状态代码
默认情况下,插件会在ETag与如果-none-match请求头指定的Etag相等时发送304状态代码.
这常常是理想的行为,但可以通过设置被禁用 replyWith304: false。 。 。 .
承认
Fnv1a逻辑来自Travis Webb(翻译:) 的,为: https://github.com/tjwebb/fnv-plus (中文(简体) ),实际执行有助于 fnv-plus 以 @ 德苏塔克 内 https://github.com/tjwebb/fnv-plus/pull/9 (中文(简体) ),并改编自 @ SukkaW (英语) 用于支持缓冲.
基准
生成一个母鹿总是比生成一个母鹿慢。 生成速度也取决于有效载荷大小和类型(缓冲或弦):
- 对于很小的有效载荷( < 2克b),使用
'fnv1a' - 2 mb 以上的缓冲器,使用
'md5' - 在所有其他情况下,使用
'sha1'(默认) - YMMV,见 这个问题 其他算法,如小有效载荷的crc32和大缓冲器的murhash3-wasm,其性能优于上述建议
- 任何电阻生成都会导致至少10%的操作量减少(对于巨大的有效载荷,操作量减少50%)
许可证
许可证根据 麻省理工学院。 。 。 .