
为什么选择Hono用于边缘?
Hono是一个小巧、快速的Web框架,专为边缘运行时设计。它可以在Cloudflare Workers、Deno Deploy、Bun、Node.js等上运行——同一份代码,任何运行时。
快速开始
npm create hono@latest my-app
cd my-app && npm install
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
app.get('/', (c) => c.text('Hello Hono!'))
const userSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
})
app.post('/users', zValidator('json', userSchema), async (c) => {
const data = c.req.valid('json')
// data is typed!
const user = await createUser(data)
return c.json(user, 201)
})
app.get('/users/:id', async (c) => {
const id = c.req.param('id')
const user = await getUserById(id)
if (!user) return c.notFound()
return c.json(user)
})
export default app
中间件
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { timing } from 'hono/timing'
import { bearerAuth } from 'hono/bearer-auth'
const app = new Hono()
// 内置中间件
app.use('*', logger())
app.use('*', cors())
app.use('*', timing())
// 特定路由上的认证中间件
app.use('/api/*', bearerAuth({ token: process.env.API_TOKEN! }))
Cloudflare Workers(使用D1、KV、R2)
// worker.ts
import { Hono } from 'hono'
type Bindings = {
DB: D1Database // 边缘SQLite
KV: KVNamespace // 键值存储
BUCKET: R2Bucket // 对象存储
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/posts', async (c) => {
const { results } = await c.env.DB.prepare(
'SELECT * FROM posts ORDER BY created_at DESC LIMIT 20'
).all()
return c.json(results)
})
app.get('/cache/:key', async (c) => {
const key = c.req.param('key')
const value = await c.env.KV.get(key)
if (!value) return c.notFound()
return c.text(value)
})
export default app
RPC客户端(类型安全,类似tRPC)
// 服务端
const routes = app
.get('/users', (c) => c.json({ users: [] }))
.post('/users', zValidator('json', userSchema), (c) => {
return c.json({ id: '1', ...c.req.valid('json') })
})
export type AppType = typeof routes
// 客户端(前端或其他服务)
import { hc } from 'hono/client'
const client = hc<AppType>('https://api.example.com')
const res = await client.users.$get()
const { users } = await res.json() // 完全类型化!
性能数据
Hono是最快的Node.js框架之一:
- ~200k req/s 在Cloudflare Workers上
- ~140k req/s 在Bun上
- 启动时间:< 1ms(完美应对冷启动)