workers
is a package to run an HTTP server written in Go on Cloudflare Workers.- This package can easily serve http.Handler on Cloudflare Workers.
- Caution: This is an experimental project.
- serve http.Handler
- R2
- Head
- Get
- Put
- Delete
- List
- Options for R2 methods
- KV
- Get
- List
- Put
- Delete
- Options for KV methods
- Cache API
- Durable Objects
- Calling stubs
- D1 (alpha)
- Environment variables
- FetchEvent
- Cron Triggers
- TCP Sockets
- Queues
- Producer
- Consumer
go get github.com/syumai/workers
implement your http.Handler and give it to workers.Serve()
.
func main() {
var handler http.HandlerFunc = func (w http.ResponseWriter, req *http.Request) { ... }
workers.Serve(handler)
}
or just call http.Handle
and http.HandleFunc
, then invoke workers.Serve()
with nil.
func main() {
http.HandleFunc("/hello", func (w http.ResponseWriter, req *http.Request) { ... })
workers.Serve(nil) // if nil is given, http.DefaultServeMux is used.
}
For concrete examples, see _examples
directory.
First, please install the following tools:
- Node.js (and npm)
- wrangler
- You can install it by running
npm install -g wrangler
.
- You can install it by running
- Go 1.21.3 or later
- gonew
- You can install it by running
go install golang.org/x/tools/cmd/gonew@latest
- You can install it by running
After installation, please run the following commands.
gonew github.com/syumai/workers/_templates/cloudflare/worker-go your.module/my-app # e.g. github.com/syumai/my-app
cd my-app
go mod tidy
make dev # start running dev server
curl http://localhost:8787/hello # outputs "Hello!"
If you want a more detailed description, please refer to the README.md file in the generated directory.
To deploy a Worker, the following steps are required.
- Create a worker project using wrangler.
- Build a Wasm binary.
- Upload a Wasm binary with a JavaScript code to load and instantiate Wasm (for entry point).
The worker-go template contains all the required files, so I recommend using this template.
But Go (not TinyGo) with many dependencies may exceed the size limit of the Worker (3MB for free plan, 10MB for paid plan). In that case, you can use the TinyGo template instead.
You can do both through GitHub Issues. If you want to have a more casual conversation, please use the Discord server.