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 上:
brew tap azure/functions
brew install azure-functions-core-tools@4
其他操作系统请参考以下链接:
2. 设置
在当前文件夹中创建一个 TypeScript Node.js V4 项目。
func init --typescript
修改 host 的默认路由前缀。将以下属性添加到 host.json
的根 json 对象中:
"extensions": {
"http": {
"routePrefix": ""
}
}
INFO
Azure Functions 默认的路由前缀是 /api
。如果你不按上面方法修改,务必让所有 Hono 路由以 /api
开头。
现在可以安装 Hono 和 Azure Functions Adapter:
npm
npm i @marplex/hono-azurefunc-adapter hono
yarn
yarn add @marplex/hono-azurefunc-adapter hono
pnpm
pnpm add @marplex/hono-azurefunc-adapter hono
bun
bun add @marplex/hono-azurefunc-adapter hono
3. Hello World
创建 src/app.ts
:
// src/app.ts
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Azure Functions!'))
export default app
创建 src/functions/httpTrigger.ts
:
// src/functions/httpTrigger.ts
import { app } from '@azure/functions'
import { azureHonoHandler } from '@marplex/hono-azurefunc-adapter'
import honoApp from '../app'
app.http('httpTrigger', {
methods: [
// 添加所有支持的 HTTP 方法
'GET',
'POST',
'DELETE',
'PUT',
],
authLevel: 'anonymous',
route: '{*proxy}',
handler: azureHonoHandler(honoApp.fetch),
})
4. 运行
本地运行开发服务器,然后在浏览器访问 http://localhost:7071
。
npm
npm run start
yarn
yarn start
pnpm
pnpm start
bun
bun run start
5. 部署
INFO 在部署到 Azure 之前,你需要在云环境中创建一些资源。请参考官方文档 Create supporting Azure resources for your function。
构建项目:
npm
npm run build
yarn
yarn build
pnpm
pnpm build
bun
bun run build
将你的项目部署到 Azure Cloud 中的 Function App,替换 <YourFunctionAppName>
为你的应用名称:
func azure functionapp publish <YourFunctionAppName>