IP Restriction 中间件
IP Restriction 中间件可基于访问者的 IP 地址限制资源访问。
导入
ts
import { Hono } from 'hono'
import { ipRestriction } from 'hono/ip-restriction'用法
以下示例适用于运行在 Bun 上的应用,仅允许本地访问。将要拒绝的规则写在 denyList 中,要允许的规则写在 allowList 中。
ts
import { Hono } from 'hono'
import { getConnInfo } from 'hono/bun'
import { ipRestriction } from 'hono/ip-restriction'
const app = new Hono()
app.use(
'*',
ipRestriction(getConnInfo, {
denyList: [],
allowList: ['127.0.0.1', '::1'],
})
)
app.get('/', (c) => c.text('Hello Hono!'))请将适用于你环境的 ConnInfo 助手 所提供的 getConnInfo 作为 ipRestriction 的第一个参数。例如在 Deno 中可以这样写:
ts
import { getConnInfo } from 'hono/deno'
import { ipRestriction } from 'hono/ip-restriction'
// ...
app.use(
'*',
ipRestriction(getConnInfo, {
// ...
})
)规则
编写规则时可遵循以下格式。
IPv4
192.168.2.0- 固定 IP 地址192.168.2.0/24- CIDR 表示法*- 全部地址
IPv6
::1- 固定 IP 地址::1/10- CIDR 表示法*- 全部地址
错误处理
若要自定义错误响应,可通过第三个参数返回一个 Response。
ts
app.use(
'*',
ipRestriction(
getConnInfo,
{
denyList: ['192.168.2.0/24'],
},
async (remote, c) => {
return c.text(`Blocking access from ${remote.addr}`, 403)
}
)
)