目前Cloudflare Worker只支持四种Lang Runtime和WebAssembly,那么可以编译为Wasm的语言也就可以部署到Worker里

部署前环境准备

Node.js

How to Install

Tinygo安装

由于官方Golang编译为Wasm的优化实在太差劲,所以直接采用Tinygo来编译Wasm,Tinygo先会将Golang代码转换为LLVM的中间表示(LR),然后通过LLVM的后端(LLC),然后将这些IR编译为标准的WebAssembly指令,所以Tinygo编译出来的Wasm文件比官方Golang编译的文件小很多。

Tinygo Install

由于最新版本tinygo net包引入了bug,这里手动替换为最新的版本pr#53

wget https://raw.githubusercontent.com/tinygo-org/net/refs/heads/main/http/roundtrip_js.go
TINYGO_PATH=$(dirname $(dirname $(which tinygo)))
TARGET_FILE="$TINYGO_PATH/src/net/http/roundtrip_js.go"
cp roundtrip_js.go "$TARGET_FILE"

创建Cloudflare Worker工程

1.初始化Workers项目

npm create cloudflare@latest -- --template github.com/syumai/workers/_templates/cloudflare/worker-tinygo

2.初始化Worker Golang

cd my-tinygo-app
go mod init
go mod tidy

3.启动Web服务器

npm start
curl http://localhost:8787/hello

4.部署到Workers

npm deploy

5.然后打开