mcpField
H
hono-core

hono-core

github.com/bobmatnyc开发78490 次安装15 周前更新
代码仓库

关于 hono-core

Hono 是面向 API 开发者的 TypeScript 优先 Web 框架,适用于边缘、无服务器及其他运行时。它基于 Web 标准 API,支持类型化路由和中间件。

主要功能

  1. 01基于 Web 标准的 API
  2. 02支持多种运行时
  3. 03快速 RegExpRouter 路由
  4. 04TypeScript 类型推断
  5. 05中间件生态

适用场景

  1. 01构建边缘环境 API
  2. 02让同一代码库运行于多种运行时
  3. 03创建类型化 HTTP 路由
  4. 04添加 CORS、身份验证或压缩

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill hono-core

安装后在 Claude Code 中输入/hono-core确认已加载。

附带文件metadata.json

详细介绍

Hono - 超高速 Web 框架

概述

Hono 是一个基于 Web 标准构建的小巧、简单且超高速的 Web 框架。它使用同一套代码,可运行于 Cloudflare Workers、Deno、Bun、Node.js 等环境。这个名字在日语中意为“火焰”。

主要特性:

  • 基于 Web 标准(Request/Response/fetch)
  • 支持多种运行时:Cloudflare Workers、Deno、Bun、Node.js、Vercel、AWS Lambda
  • 使用 RegExpRouter 实现超高速路由
  • 一流的 TypeScript 支持
  • 轻量(压缩后约 14KB)
  • 丰富的中间件生态

安装:

# Create new project (recommended)
npm create hono@latest my-app

# Or install in existing project
npm install hono

# Runtime-specific adapters
npm install @hono/node-server  # Node.js

何时使用此技能

在以下情况下使用 Hono:

  • 为边缘/无服务器环境(Cloudflare Workers、Vercel Edge)构建 API
  • 需要跨运行时移植(同一份代码可运行于 Bun、Deno、Node.js)
  • 希望采用 TypeScript 优先的开发方式,并获得出色的类型推断
  • 构建轻量、高性能的 API
  • 需要用于常见模式(CORS、身份验证、压缩)的内置中间件

Hono 与其他框架的对比:

  • Hono:支持多种运行时、遵循 Web 标准、超高速、针对边缘环境优化
  • Express:仅支持 Node.js,生态更大,速度较慢
  • Fastify:仅支持 Node.js,基于 schema,性能良好
  • Elysia:仅支持 Bun,性能出色,API 风格不同

核心概念

创建应用
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Hono!'))

export default app

使用 TypeScript 泛型(用于绑定/变量):

type Bindings = {
  DATABASE_URL: string
  API_KEY: string
}

type Variables = {
  user: { id: string; name: string }
}

const app = new Hono<{ Bindings: Bindings; Variables: Variables }>()
上下文对象(c)

上下文 c 提供对请求数据和响应方法的访问:

app.get('/users/:id', async (c) => {
  // Request data
  const id = c.req.param('id')           // Path parameter
  const query = c.req.query('sort')       // Query parameter ?sort=asc
  const queries = c.req.queries('tags')   // Multiple: ?tags=a&tags=b
  const header = c.req.header('Authorization')
  const body = await c.req.json()         // JSON body
  const form = await c.req.formData()     // Form data

  // Environment (Cloudflare Workers bindings)
  const db = c.env.DATABASE_URL

  // Custom variables (set by middleware)
  const user = c.get('user')

  // Response methods
  return c.text('Plain text')
  return c.json({ id, name: 'User' })
  return c.html('<h1>Hello</h1>')
  return c.redirect('/login')
  return c.notFound()
})
响应方法
// Text response
c.text('Hello', 200)

// JSON response
c.json({ message: 'Success' }, 201)
c.json({ error: 'Not found' }, 404)

// HTML response
c.html('<h1>Hello</h1>')

// Redirect
c.redirect('/login')           // 302 default
c.redirect('/login', 301)      // Permanent redirect

// Headers
c.header('X-Custom', 'value')
c.header('Cache-Control', 'max-age=3600')

// Streaming
c.streamText(async (stream) => {
  await stream.write('Hello ')
  await stream.write('World!')
})

// Raw Response
return new Response('Raw', { status: 200 })

路由模式

基本路由
const app = new Hono()

// HTTP methods
app.get('/users', getUsers)
app.post('/users', createUser)
app.put('/users/:id', updateUser)
app.delete('/users/:id', deleteUser)
app.patch('/users/:id', patchUser)

// All methods
app.all('/webhook', handleWebhook)

// Custom methods
app.on('PURGE', '/cache', purgeCache)
app.on(['GET', 'POST'], '/form', handleForm)
路径参数
// Single parameter
app.get('/users/:id', (c) => {
  const id = c.req.param('id')
  return c.json({ id })
})

// Multiple parameters
app.get('/posts/:postId/comments/:commentId', (c) => {
  const { postId, commentId } = c.req.param()
  return c.json({ postId, commentId })
})

// Optional parameter
app.get('/api/animal/:type?', (c) => {
  const type = c.req.param('type') || 'all'
  return c.json({ type })
})

// Regex validation
app.get('/posts/:id{[0-9]+}', (c) => {
  const id = c.req.param('id')  // Only numeric IDs
  return c.json({ id })
})

// Wildcards
app.get('/files/*', (c) => {
  const path = c.req.param('*')  // Everything after /files/
  return c.text(`File: ${path}`)
})
路由分组
// Using app.route()
const api = new Hono()
api.get('/users', getUsers)
api.get('/posts', getPosts)

const app = new Hono()
app.route('/api/v1', api)  // /api/v1/users, /api/v1/posts

// Using basePath()
const v2 = new Hono().basePath('/api/v2')
v2.get('/users', getUsers)  // /api/v2/users

// Chaining
app
  .get('/a', handlerA)
  .post('/b', handlerB)
  .delete('/c', handlerC)
路由组织(多文件)
// routes/users.ts
import { Hono } from 'hono'

const users = new Hono()

users.get('/', async (c) => {
  return c.json({ users: [] })
})

users.post('/', async (c) => {
  const body = await c.req.json()
  return c.json({ created: body }, 201)
})

users.get('/:id', async (c) => {
  const id = c.req.param('id')
  return c.json({ id })
})

export default users

// app.ts
import { Hono } from 'hono'
import users from './routes/users'
import posts from './routes/posts'

const app = new Hono()

app.route('/users', users)
app.route('/posts', posts)

export default app

处理器模式

内联处理器
// Simple handler
app.get('/hello', (c) => c.text('Hello!'))

// Async handler
app.get('/users', async (c) => {
  const users = await fetchUsers()
  return c.json({ users })
})

// Multiple handlers (middleware chain)
app.get('/admin', authenticate, authorize, (c) => {
  return c.json({ admin: true })
})
使用工厂创建类型安全的处理器
import { createFactory } from 'hono/factory'

const factory = createFactory<{ Bindings: Bindings }>()

// Create typed handler
const getUser = factory.createHandlers(async (c) => {
  const id = c.req.param('id')
  const db = c.env.DATABASE_URL  // Typed!
  return c.json({ id })
})

app.get('/users/:id', ...getUser)

错误处理

内置错误处理
import { HTTPException } from 'hono/http-exception'

app.get('/users/:id', async (c) => {
  const user = await findUser(c.req.param('id'))

  if (!user) {
    throw new HTTPException(404, { message: 'User not found' })
  }

  return c.json(user)
})

// Global error handler
app.onError((err, c) => {
  console.error(`${err}`)

  if (err instanceof HTTPException) {
    return err.getResponse()
  }

  return c.json({ error: 'Internal Server Error' }, 500)
})

// Not found handler
app.notFound((c) => {
  return c.json({ error: 'Route not found' }, 404)
})
自定义错误类
class ValidationError extends HTTPException {
  constructor(errors: string[]) {
    super(400, {
      message: 'Validation failed',
      cause: errors
    })
  }
}

class AuthenticationError extends HTTPException {
  constructor() {
    super(401, { message: 'Authentication required' })
  }
}

特定运行时的导出

Cloudflare Workers
// src/index.ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Cloudflare!'))

export default app
Node.js
// src/index.ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Node!'))

serve({
  fetch: app.fetch,
  port: 3000
})
Bun
// src/index.ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))

export default {
  port: 3000,
  fetch: app.fetch
}
Deno
// main.ts
import { Hono } from 'npm:hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Deno!'))

Deno.serve(app.fetch)

最佳实践

将处理器内联编写(而非使用控制器)
// CORRECT: Inline handlers with proper type inference
app.get('/users/:id', async (c) => {
  const id = c.req.param('id')  // Type: string
  return c.json({ id })
})

// AVOID: Controller-style (loses type inference)
class UserController {
  getUser(c: Context) {
    const id = c.req.param('id')  // Type: string | undefined
    return c.json({ id })
  }
}
使用模块化路由
// CORRECT: Split routes by domain
// routes/users.ts
export const users = new Hono()
  .get('/', listUsers)
  .post('/', createUser)
  .get('/:id', getUser)

// app.ts
app.route('/users', users)
为所有内容添加类型
// Define your environment bindings
type Bindings = {
  DATABASE_URL: string
  JWT_SECRET: string
  MY_KV: KVNamespace
}

// Pass to Hono
const app = new Hono<{ Bindings: Bindings }>()

// Now c.env is fully typed
app.get('/', (c) => {
  const url = c.env.DATABASE_URL  // string
  const kv = c.env.MY_KV          // KVNamespace
})

快速参考

常用上下文方法
方法说明示例
c.req.param(name)获取路径参数c.req.param('id')
c.req.query(name)获取查询参数c.req.query('page')
c.req.header(name)获取请求头c.req.header('Authorization')
c.req.json()解析 JSON 请求体await c.req.json()
c.req.formData()解析表单数据await c.req.formData()
c.text(str, status)文本响应c.text('OK', 200)
c.json(obj, status)JSON 响应c.json({}, 201)
c.html(str)HTML 响应c.html('<h1>Hi</h1>')
c.redirect(url)重定向c.redirect('/login')
c.header(k, v)设置响应头c.header('X-Custom', 'val')
c.set(key, val)设置上下文变量c.set('user', user)
c.get(key)获取上下文变量c.get('user')
c.env环境绑定c.env.API_KEY
HTTP 方法
app.get(path, ...handlers)
app.post(path, ...handlers)
app.put(path, ...handlers)
app.delete(path, ...handlers)
app.patch(path, ...handlers)
app.options(path, ...handlers)
app.head(path, ...handlers)
app.all(path, ...handlers)
app.on(method, path, ...handlers)

相关技能

  • hono-middleware - 中间件模式与组合
  • hono-validation - 使用 Zod 验证请求
  • hono-rpc - 类型安全的 RPC 客户端
  • hono-testing - 测试模式
  • hono-jsx - 服务端 JSX 渲染
  • hono-cloudflare - Cloudflare Workers 部署

版本:Hono 4.x 最后更新:2025 年 1 月 许可证:MIT

评论

支持 Markdown