@elithrar/ 工人- hono- rate- 限制
Cloudflare工人的Hono中间软件 利率限制约束。 。 。 .
安装
npm install @elithrar/workers-hono-rate-limit
使用量
- 添加限制利率
wrangler.toml(或wrangler.jsonc(中文(简体) ) - 定义 a
RateLimitKeyFunc返回按键以限制速率 - 应用
rateLimit中间软件到您的路径
# wrangler.toml
[[ratelimits]]
binding = "RATE_LIMITER"
namespace_id = "1001"
# 25 requests per 10 seconds
simple = { limit = 25, period = 10 }
import { rateLimit, RateLimitBinding, RateLimitKeyFunc } from "@elithrar/workers-hono-rate-limit";
import { Hono } from "hono";
type Bindings = {
RATE_LIMITER: RateLimitBinding;
};
const app = new Hono<{ Bindings: Bindings }>();
// Rate limit on each API token
const getKey: RateLimitKeyFunc = (c) => c.req.header("Authorization") || "";
// Apply rate limiting to all routes
app.use("*", (c, next) => rateLimit(c.env.RATE_LIMITER, getKey)(c, next));
app.get("/", (c) => c.text("hello!"));
export default app;
您可以创建多个 rateLimit 实例,每个使用大小写都有不同的配置和关键函数,或者通过 app.use。 。 。 .
同步密钥函数
这个 keyFunc 如果您需要查询用户信息, 也可以进行同步 :
const getKey: RateLimitKeyFunc = async (c) => {
const user = await validateToken(c.req.header("Authorization"));
return user?.id || "";
};
页:1
- 密钥应代表用户或一类用户的独特特征. 良好的选择包括API密钥,用户ID,或租户ID.
- 避免使用IP地址或位置作为密钥——这些可以被许多用户共享.
- 狦
keyFunc返回空字符串,对该请求绕过速率限制.
许可证
Apache 2.0获得许可. 详情见LICENSE文件.