36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
const isJSON = require("koa-is-json");
|
||
const zlib = require("zlib");
|
||
|
||
module.exports = (options) => {
|
||
return async function gzip(ctx, next) {
|
||
// 限制域名访问 added by steven @2023-07-11
|
||
const ipCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
|
||
const host = ctx.request.host.indexOf(":")
|
||
? ctx.request.host.split(":")[0]
|
||
: ctx.request.host;
|
||
if (ipCheck.test(host)) {
|
||
ctx.status = 200;
|
||
ctx.body = `<!DOCTYPE html><html><head><title>访问禁止</title></head><body>只允许域名方式访问</body></html>`;
|
||
// ctx.throw(401, "只允许域名访问");
|
||
return;
|
||
}
|
||
/////
|
||
await next();
|
||
|
||
// 后续中间件执行完成后将响应体转换成 gzip
|
||
let body = ctx.body;
|
||
if (!body) return;
|
||
|
||
// 支持 options.threshold
|
||
if (options.threshold && ctx.length < options.threshold) return;
|
||
|
||
if (isJSON(body)) body = JSON.stringify(body);
|
||
|
||
// 设置 gzip body,修正响应头
|
||
const stream = zlib.createGzip();
|
||
stream.end(body);
|
||
ctx.body = stream;
|
||
ctx.set("Content-Encoding", "gzip");
|
||
};
|
||
};
|