使用 Worker 为 bot 分数较低的请求添加可配置的延迟。
订阅了 Bot Management 和 Workers 的客户可以使用下面的模板,向可能来自 bot 的请求引入延迟。
该模板设置了最小和最大延迟,并对 bot 分数低于 30 且 URI 路径以 /exampleURI 开头的请求实施延迟。
// 可配置的变量
const PATH_START = "/exampleURI";
const DELAY_FROM = 5; // 单位为秒
const DELAY_TO = 10; // 单位为秒
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const botScore = request.cf.botManagement.score;
if (url.pathname.startsWith(PATH_START) && botScore < 30) {
// 在 DELAY_FROM 和 DELAY_TO 秒之间产生随机延迟
const delay =
Math.floor(Math.random() * (DELAY_TO - DELAY_FROM + 1)) + DELAY_FROM;
await new Promise((resolve) => setTimeout(resolve, delay * 1000));
// 获取原始请求
return fetch(request);
}
// 无延迟地获取原始请求
return fetch(request);
},
};// 可配置的变量
const PATH_START = '/exampleURI';
const DELAY_FROM = 5; // 单位为秒
const DELAY_TO = 10; // 单位为秒
export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url);
const botScore = request.cf.botManagement.score
if (url.pathname.startsWith(PATH_START) && botScore < 30) {
// 在 DELAY_FROM 和 DELAY_TO 秒之间产生随机延迟
const delay = Math.floor(Math.random() * (DELAY_TO - DELAY_FROM + 1)) + DELAY_FROM;
await new Promise(resolve => setTimeout(resolve, delay * 1000));
// 获取原始请求
return fetch(request);
}
// 无延迟地获取原始请求
return fetch(request);
},
} satisfies ExportedHandler<Env>;