Azure Functions

Azure Functions 是 Microsoft Azure 提供的无服务器(serverless)平台。你可以在响应事件时运行代码,并且它会自动管理底层的计算资源。

Hono 最初并不是为 Azure Functions 设计的,但借助 Azure Functions Adapter,它也可以运行在 Azure Functions 上。

它支持运行在 Node.js 18 或以上版本的 Azure Functions V4

1. 安装 CLI

要创建 Azure Function,你必须先安装 Azure Functions Core Tools

在 macOS 上:

  1. brew tap azure/functions
  2. brew install azure-functions-core-tools@4

其他操作系统请参考以下链接:

2. 设置

在当前文件夹中创建一个 TypeScript Node.js V4 项目。

  1. func init --typescript

修改 host 的默认路由前缀。将以下属性添加到 host.json 的根 json 对象中:

  1. "extensions": {
  2. "http": {
  3. "routePrefix": ""
  4. }
  5. }

INFO Azure Functions 默认的路由前缀是 /api。如果你不按上面方法修改,务必让所有 Hono 路由以 /api 开头。

现在可以安装 Hono 和 Azure Functions Adapter:

npm

  1. npm i @marplex/hono-azurefunc-adapter hono

yarn

  1. yarn add @marplex/hono-azurefunc-adapter hono

pnpm

  1. pnpm add @marplex/hono-azurefunc-adapter hono

bun

  1. bun add @marplex/hono-azurefunc-adapter hono

3. Hello World

创建 src/app.ts

  1. // src/app.ts
  2. import { Hono } from 'hono'
  3. const app = new Hono()
  4. app.get('/', (c) => c.text('Hello Azure Functions!'))
  5. export default app

创建 src/functions/httpTrigger.ts

  1. // src/functions/httpTrigger.ts
  2. import { app } from '@azure/functions'
  3. import { azureHonoHandler } from '@marplex/hono-azurefunc-adapter'
  4. import honoApp from '../app'
  5. app.http('httpTrigger', {
  6. methods: [
  7. // 添加所有支持的 HTTP 方法
  8. 'GET',
  9. 'POST',
  10. 'DELETE',
  11. 'PUT',
  12. ],
  13. authLevel: 'anonymous',
  14. route: '{*proxy}',
  15. handler: azureHonoHandler(honoApp.fetch),
  16. })

4. 运行

本地运行开发服务器,然后在浏览器访问 http://localhost:7071

npm

  1. npm run start

yarn

  1. yarn start

pnpm

  1. pnpm start

bun

  1. bun run start

5. 部署

INFO 在部署到 Azure 之前,你需要在云环境中创建一些资源。请参考官方文档 Create supporting Azure resources for your function

构建项目:

npm

  1. npm run build

yarn

  1. yarn build

pnpm

  1. pnpm build

bun

  1. bun run build

将你的项目部署到 Azure Cloud 中的 Function App,替换 <YourFunctionAppName> 为你的应用名称:

  1. func azure functionapp publish <YourFunctionAppName>