Appearance
压缩中间件
🌐 Compress Middleware
此中间件根据 Accept-Encoding 请求头压缩响应主体。
🌐 This middleware compresses the response body, according to Accept-Encoding request header.
INFO
注意:在 Cloudflare Workers 和 Deno Deploy 上,响应主体将自动压缩,因此无需使用此中间件。
导入
🌐 Import
ts
import { Hono } from 'hono'
import { compress } from 'hono/compress'用法
🌐 Usage
ts
const app = new Hono()
app.use(compress())选项
🌐 Options
optional 编码: 'gzip' | 'deflate'
用于允许响应压缩的压缩方案。可以是 gzip 或 deflate。如果未定义,则两者都允许,并将根据 Accept-Encoding 头使用。如果未提供此选项,并且客户端在 Accept-Encoding 头中提供了两者,则优先使用 gzip。
🌐 The compression scheme to allow for response compression. Either gzip or deflate. If not defined, both are allowed and will be used based on the Accept-Encoding header. gzip is prioritized if this option is not provided and the client provides both in the Accept-Encoding header.
optional 阈值:number
压缩的最小字节数。默认值为1024字节。
🌐 The minimum size in bytes to compress. Defaults to 1024 bytes.
optional 内容类型过滤器: RegExp | (contentType: string) => boolean
一个 RegExp 或函数,用于根据其 Content-Type 判断响应是否应该被压缩。默认情况下,使用内置的可压缩内容类型列表。
🌐 A RegExp or function to determine whether the response should be compressed based on its Content-Type. By default, a built-in list of compressible Content-Types is used.
你可以传递一个 RegExp 来仅压缩匹配的内容类型:
🌐 You can pass a RegExp to compress only matching Content-Types:
ts
// Compress only JSON responses
app.use(compress({ contentTypeFilter: /^application\/json/ }))或者传入一个函数以实现自定义逻辑。内置的 COMPRESSIBLE_CONTENT_TYPE_REGEX 也被导出,因此你可以扩展默认行为:
🌐 Or pass a function for custom logic. The built-in COMPRESSIBLE_CONTENT_TYPE_REGEX is also exported so you can extend the default behavior:
ts
import {
compress,
COMPRESSIBLE_CONTENT_TYPE_REGEX,
} from 'hono/compress'
// Compress the default Content-Types plus a custom one
app.use(
compress({
contentTypeFilter: (type) =>
COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) ||
type === 'application/x-myformat',
})
)