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)
}
)
)