Skip to content

Cloudflare Workers

Cloudflare Workers 是 Cloudflare CDN 上的 JavaScript 边缘运行时。

¥Cloudflare Workers is a JavaScript edge runtime on Cloudflare CDN.

你可以在本地开发应用并使用 Wrangler 使用几个命令发布它。Wrangler 包含 trans 编译器,因此我们可以使用 TypeScript 编写代码。

¥You can develop the application locally and publish it with a few commands using Wrangler. Wrangler includes trans compiler, so we can write the code with TypeScript.

让我们用 Hono 为 Cloudflare Workers 制作你的第一个应用。

¥Let’s make your first application for Cloudflare Workers with Hono.

1. 设置

¥ Setup

Cloudflare Workers 的入门程序可用。使用 "create-hono" 命令启动你的项目。为此示例选择 cloudflare-workers 模板。

¥A starter for Cloudflare Workers is available. Start your project with "create-hono" command. Select cloudflare-workers template for this example.

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

移至 my-app 并安装依赖。

¥Move to my-app and install the dependencies.

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

2. Hello World

按如下方式编辑 src/index.ts

¥Edit src/index.ts like below.

ts
import { Hono } from 'hono'
const app = new Hono()

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

export default app

3. 运行

¥ Run

在本地运行开发服务器。然后,在你的 Web 浏览器中访问 http://localhost:8787

¥Run the development server locally. Then, access http://localhost:8787 in your web browser.

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

更改端口编号

¥Change port number

如果你需要更改端口号,可以按照此处的说明更新 wrangler.toml / wrangler.json / wrangler.jsonc 文件:Wrangler 配置

¥If you need to change the port number you can follow the instructions here to update wrangler.toml / wrangler.json / wrangler.jsonc files: Wrangler Configuration

或者,你可以按照此处的说明设置 CLI 选项:Wrangler CLI

¥Or, you can follow the instructions here to set CLI options: Wrangler CLI

4. 部署

¥ Deploy

如果你有 Cloudflare 账户,可以部署到 Cloudflare。在 package.json 中,需要将 $npm_execpath 更改为你选择的包管理器。

¥If you have a Cloudflare account, you can deploy to Cloudflare. In package.json, $npm_execpath needs to be changed to your package manager of choice.

sh
npm run deploy
sh
yarn deploy
sh
pnpm run deploy
sh
bun run deploy

就这些!

¥That's all!

服务工作线程模式或模块工作线程模式

¥Service Worker mode or Module Worker mode

有两种用于编写 Cloudflare Workers 的语法。Module Worker 模式和 Service Worker 模式。使用 Hono,你可以同时使用两种语法编写,但我们建议使用 Module Worker 模式,以便绑定变量本地化。

¥There are two syntaxes for writing the Cloudflare Workers. Module Worker mode and Service Worker mode. Using Hono, you can write with both syntax, but we recommend using Module Worker mode so that binding variables are localized.

ts
// Module Worker
export default app
ts
// Service Worker
app.fire()

将 Hono 与其他事件处理程序一起使用

¥Using Hono with other event handlers

你可以在 Module Worker 模式下将 Hono 与其他事件处理程序(例如 scheduled)集成。

¥You can integrate Hono with other event handlers (such as scheduled) in Module Worker mode.

为此,请将 app.fetch 导出为模块的 fetch 处理程序,然后根据需要实现其他处理程序:

¥To do this, export app.fetch as the module's fetch handler, and then implement other handlers as needed:

ts
const app = new Hono()

export default {
  fetch: app.fetch,
  scheduled: async (batch, env) => {},
}

提供静态文件

¥Serve static files

如果你想要提供静态文件,你可以使用 Cloudflare Workers 的 静态资源功能。指定 wrangler.toml 中文件的目录:

¥If you want to serve static files, you can use the Static Assets feature of Cloudflare Workers. Specify the directory for the files in wrangler.toml:

toml
assets = { directory = "public" }

然后创建 public 目录并将文件放在那里。例如,./public/static/hello.txt 将作为 /static/hello.txt 提供。

¥Then create the public directory and place the files there. For instance, ./public/static/hello.txt will be served as /static/hello.txt.

.
├── package.json
├── public
│   ├── favicon.ico
│   └── static
│       └── hello.txt
├── src
│   └── index.ts
└── wrangler.toml

类型

¥Types

如果你想拥有 worker 类型,则必须安装 @cloudflare/workers-types

¥You have to install @cloudflare/workers-types if you want to have workers types.

sh
npm i --save-dev @cloudflare/workers-types
sh
yarn add -D @cloudflare/workers-types
sh
pnpm add -D @cloudflare/workers-types
sh
bun add --dev @cloudflare/workers-types

测试

¥Testing

对于测试,我们建议使用 @cloudflare/vitest-pool-workers。请参阅 examples 进行设置。

¥For testing, we recommend using @cloudflare/vitest-pool-workers. Refer to examples for setting it up.

如果有以下应用。

¥If there is the application below.

ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Please test me!'))

我们可以使用此代码测试它是否返回 "200 OK" 响应。

¥We can test if it returns "200 OK" Response with this code.

ts
describe('Test the application', () => {
  it('Should return 200 response', async () => {
    const res = await app.request('http://localhost/')
    expect(res.status).toBe(200)
  })
})

绑定

¥Bindings

在 Cloudflare Workers 中,我们可以绑定环境值、KV 命名空间、R2 bucket 或 Durable Object。你可以在 c.env 中访问它们。如果你将绑定的 "类型结构" 作为泛型传递给 Hono,它将具有类型。

¥In the Cloudflare Workers, we can bind the environment values, KV namespace, R2 bucket, or Durable Object. You can access them in c.env. It will have the types if you pass the "type struct" for the bindings to the Hono as generics.

ts
type Bindings = {
  MY_BUCKET: R2Bucket
  USERNAME: string
  PASSWORD: string
}

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

// Access to environment values
app.put('/upload/:key', async (c, next) => {
  const key = c.req.param('key')
  await c.env.MY_BUCKET.put(key, c.req.body)
  return c.text(`Put ${key} successfully!`)
})

在中间件中使用变量

¥Using Variables in Middleware

这是 Module Worker 模式的唯一情况。如果要在中间件中使用变量或秘密变量,例如基本身份验证中间件中的 "username" 或 "password",则需要像下面这样编写。

¥This is the only case for Module Worker mode. If you want to use Variables or Secret Variables in Middleware, for example, "username" or "password" in Basic Authentication Middleware, you need to write like the following.

ts
import { basicAuth } from 'hono/basic-auth'

type Bindings = {
  USERNAME: string
  PASSWORD: string
}

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

//...

app.use('/auth/*', async (c, next) => {
  const auth = basicAuth({
    username: c.env.USERNAME,
    password: c.env.PASSWORD,
  })
  return auth(c, next)
})

同样适用于 Bearer 身份验证中间件、JWT 身份验证或其他。

¥The same is applied to Bearer Authentication Middleware, JWT Authentication, or others.

从 GitHub Actions 部署

¥Deploy from GitHub Actions

在通过 CI 将代码部署到 Cloudflare 之前,你需要一个 Cloudflare 令牌。你可以从 用户 API 令牌 进行管理。

¥Before deploying code to Cloudflare via CI, you need a Cloudflare token. You can manage it from User API Tokens.

如果是新创建的令牌,请选择编辑 Cloudflare Workers 模板,如果你已经有另一个令牌,请确保该令牌具有相应的权限(否,令牌权限不在 Cloudflare Pages 和 Cloudflare Workers 之间共享)。

¥If it's a newly created token, select the Edit Cloudflare Workers template, if you already have another token, make sure the token has the corresponding permissions(No, token permissions are not shared between Cloudflare Pages and Cloudflare Workers).

然后转到你的 GitHub 存储库设置仪表板:Settings->Secrets and variables->Actions->Repository secrets,并添加一个名为 CLOUDFLARE_API_TOKEN 的新密钥。

¥then go to your GitHub repository settings dashboard: Settings->Secrets and variables->Actions->Repository secrets, and add a new secret with the name CLOUDFLARE_API_TOKEN.

然后在你的 Hono 项目根文件夹中创建 .github/workflows/deploy.yml,粘贴以下代码:

¥then create .github/workflows/deploy.yml in your Hono project root folder, paste the following code:

yml
name: Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

然后编辑 wrangler.toml,并在 compatibility_date 行后添加此代码。

¥then edit wrangler.toml, and add this code after compatibility_date line.

toml
main = "src/index.ts"
minify = true

一切就绪!现在推送代码并享受它。

¥Everything is ready! Now push the code and enjoy it.

本地开发时加载环境

¥Load env when local development

要配置本地开发的环境变量,请在项目根目录中创建 .dev.vars 文件。然后像使用普通环境文件一样配置环境变量。

¥To configure the environment variables for local development, create the .dev.vars file in the root directory of the project. Then configure your environment variables as you would with a normal env file.

SECRET_KEY=value
API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

有关此部分的更多信息,你可以在 Cloudflare 文档中找到:https://developers.cloudflare.com/workers/wrangler/configuration/#secrets

¥For more about this section you can find in the Cloudflare documentation: https://developers.cloudflare.com/workers/wrangler/configuration/#secrets

然后我们使用 c.env.* 获取代码中的环境变量。对于 Cloudflare Workers,必须通过 c 获取环境变量,而不是通过 process.env

¥Then we use the c.env.* to get the environment variables in our code.
For Cloudflare Workers, environment variables must be obtained via c, not via process.env.

ts
type Bindings = {
  SECRET_KEY: string
}

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

app.get('/env', (c) => {
  const SECRET_KEY = c.env.SECRET_KEY
  return c.text(SECRET_KEY)
})

在将项目部署到 Cloudflare 之前,请记住在 Cloudflare Workers 项目的配置中设置环境变量/密钥。

¥Before you deploy your project to Cloudflare, remember to set the environment variable/secrets in the Cloudflare Workers project's configuration.

有关此部分的更多信息,你可以在 Cloudflare 文档中找到:https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-the-dashboard

¥For more about this section you can find in the Cloudflare documentation: https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-the-dashboard

Hono v4.7 中文网 - 粤ICP备13048890号