BunHono集成 BunHonoIntegration

Bun Hono 集成技能是用于在Bun运行时上快速构建Web API的框架,专为高性能和轻量级设计。它支持路由、中间件、REST API、验证、错误处理等功能,适用于开发后端服务、微服务和量化交易系统API。关键词:Bun, Hono, Web框架, API开发, 后端开发, 快速开发, 量化交易

后端开发 0 次安装 0 次浏览 更新于 3/8/2026

名称: Bun Hono 集成 描述: 在Bun上使用Hono框架构建API时使用,包括路由、中间件、REST API、上下文处理或Web框架功能。 版本: 1.0.0

Bun Hono 集成

Hono 是一个快速、轻量级的Web框架,专为Bun优化。

快速开始

bun create hono my-app
cd my-app
bun install
bun run dev

基本设置

import { Hono } from "hono";

const app = new Hono();

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

app.get("/json", (c) => c.json({ message: "Hello" }));

export default app;

路由

import { Hono } from "hono";

const app = new Hono();

// HTTP方法
app.get("/users", (c) => c.json([]));
app.post("/users", (c) => c.json({ created: true }));
app.put("/users/:id", (c) => c.json({ updated: true }));
app.delete("/users/:id", (c) => c.json({ deleted: true }));

// 所有方法
app.all("/any", (c) => c.text("任何方法"));

// 路径参数
app.get("/users/:id", (c) => {
  const id = c.req.param("id");
  return c.json({ id });
});

// 多参数
app.get("/posts/:postId/comments/:commentId", (c) => {
  const { postId, commentId } = c.req.param();
  return c.json({ postId, commentId });
});

// 通配符
app.get("/files/*", (c) => {
  const path = c.req.path;
  return c.text(`文件: ${path}`);
});

// 正则类模式
app.get("/user/:id{[0-9]+}", (c) => c.json({ id: c.req.param("id") }));

export default app;

路由组

import { Hono } from "hono";

const app = new Hono();

// 分组路由
const api = new Hono();
api.get("/users", (c) => c.json([]));
api.get("/posts", (c) => c.json([]));

app.route("/api/v1", api);

// 基础路径
const app2 = new Hono().basePath("/api/v2");
app2.get("/users", (c) => c.json([])); // /api/v2/users

export default app;

请求处理

app.post("/submit", async (c) => {
  // URL和方法
  console.log(c.req.url);
  console.log(c.req.method);

  // 头信息
  const auth = c.req.header("Authorization");

  // 查询参数
  const page = c.req.query("page");
  const { limit, offset } = c.req.query();

  // 正文解析
  const json = await c.req.json();
  const text = await c.req.text();
  const form = await c.req.formData();
  const arrayBuffer = await c.req.arrayBuffer();

  // 解析正文(带验证器)
  const body = c.req.valid("json");

  return c.json({ received: true });
});

响应类型

app.get("/responses", (c) => {
  // 文本
  return c.text("Hello");

  // JSON
  return c.json({ data: "value" });

  // HTML
  return c.html("<h1>Hello</h1>");

  // 重定向
  return c.redirect("/other", 302);

  // 未找到
  return c.notFound();

  // 自定义响应
  return c.body("原始正文", 200, {
    "Content-Type": "text/plain",
  });

  // 状态
  return c.json({ error: "未找到" }, 404);

  // 头信息
  c.header("X-Custom", "value");
  return c.json({ ok: true });
});

中间件

import { Hono } from "hono";

const app = new Hono();

// 全局中间件
app.use("*", async (c, next) => {
  console.log(`${c.req.method} ${c.req.url}`);
  await next();
});

// 路径特定中间件
app.use("/api/*", async (c, next) => {
  const auth = c.req.header("Authorization");
  if (!auth) {
    return c.json({ error: "未授权" }, 401);
  }
  await next();
});

// 多中间件
app.use("/admin/*", authMiddleware, adminMiddleware);

app.get("/api/data", (c) => c.json({ data: "受保护" }));

export default app;

内置中间件

import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import { basicAuth } from "hono/basic-auth";
import { bearerAuth } from "hono/bearer-auth";
import { compress } from "hono/compress";
import { etag } from "hono/etag";
import { secureHeaders } from "hono/secure-headers";

const app = new Hono();

// CORS
app.use("*", cors());
app.use("/api/*", cors({
  origin: "https://example.com",
  allowMethods: ["GET", "POST"],
}));

// 日志
app.use("*", logger());

// 基本认证
app.use("/admin/*", basicAuth({
  username: "admin",
  password: "secret",
}));

// 承载令牌
app.use("/api/*", bearerAuth({
  token: "my-token",
}));

// 压缩
app.use("*", compress());

// ETag
app.use("*", etag());

// 安全头信息
app.use("*", secureHeaders());

export default app;

使用Zod验证

import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";

const app = new Hono();

const userSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().min(0).optional(),
});

app.post(
  "/users",
  zValidator("json", userSchema),
  (c) => {
    const user = c.req.valid("json");
    // user已类型化和验证
    return c.json({ created: user });
  }
);

// 查询验证
const querySchema = z.object({
  page: z.string().regex(/^\d+$/).optional(),
  limit: z.string().regex(/^\d+$/).optional(),
});

app.get(
  "/items",
  zValidator("query", querySchema),
  (c) => {
    const { page, limit } = c.req.valid("query");
    return c.json({ page, limit });
  }
);

export default app;

上下文变量

import { Hono } from "hono";

type Variables = {
  userId: string;
  isAdmin: boolean;
};

const app = new Hono<{ Variables: Variables }>();

app.use("*", async (c, next) => {
  c.set("userId", "123");
  c.set("isAdmin", true);
  await next();
});

app.get("/profile", (c) => {
  const userId = c.get("userId");
  const isAdmin = c.get("isAdmin");
  return c.json({ userId, isAdmin });
});

export default app;

错误处理

import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";

const app = new Hono();

// 抛出HTTP错误
app.get("/error", (c) => {
  throw new HTTPException(401, { message: "未授权" });
});

// 全局错误处理器
app.onError((err, c) => {
  if (err instanceof HTTPException) {
    return err.getResponse();
  }
  console.error(err);
  return c.json({ error: "内部服务器错误" }, 500);
});

// 未找到处理器
app.notFound((c) => {
  return c.json({ error: "未找到" }, 404);
});

export default app;

RPC模式(类型安全客户端)

// server.ts
import { Hono } from "hono";
import { hc } from "hono/client";

const app = new Hono()
  .get("/users", (c) => c.json([{ id: 1, name: "Alice" }]))
  .post("/users", async (c) => {
    const body = await c.req.json();
    return c.json({ created: body });
  });

export type AppType = typeof app;
export default app;

// client.ts
import { hc } from "hono/client";
import type { AppType } from "./server";

const client = hc<AppType>("http://localhost:3000");

// 类型安全调用
const res = await client.users.$get();
const users = await res.json(); // 已类型化!

const created = await client.users.$post({
  json: { name: "Bob" },
});

常见错误

错误 原因 修复
路由未找到 路径错误 检查路由注册
正文已读取 双重解析 读取正文一次
验证器错误 无效输入 检查模式定义
中间件顺序 执行错误 先注册中间件

何时加载参考

加载 references/middleware-list.md 当:

  • 完整中间件参考
  • 自定义中间件模式

加载 references/openapi.md 当:

  • OpenAPI/Swagger集成
  • API文档生成