用 Hono 构建 API
在 Deno 上创建可测试、可跨 runtime 部署的 Hono REST API
Hono 的优势是 API 小、基于 Web 标准,并能在多个 runtime 复用业务路由。官方 Deno starter:
deno init --npm hono --template=deno my-api
cd my-api
deno task start
最小服务
import { Hono } from "hono";
const app = new Hono();
app.get("/health", (c) => c.json({ ok: true }));
app.get("/users/:id", (c) => c.json({ id: c.req.param("id") }));
Deno.serve({ port: 8000 }, app.fetch);
不监听端口的测试
import { assertEquals } from "@std/assert";
Deno.test("GET /health", async () => {
const response = await app.request("http://localhost/health");
assertEquals(response.status, 200);
assertEquals(await response.json(), { ok: true });
});
npm 还是 JSR
Hono 同时发布到 npm 和 JSR。第三方 middleware 参与类型推断时,Hono 核心与 middleware 尽量来自同一 registry,避免重复类型实例。静态文件 helper 使用 hono/deno,需要对应的文件读取权限。
生产 API 还应增加 schema 校验、统一错误映射、CORS allowlist、body 上限、超时、request ID 与结构化日志。
官方参考:Hono on Deno、Hono middleware。