add multiple-handlers example

This commit is contained in:
syumai 2024-11-08 02:33:41 +09:00
parent 68bb0c7e08
commit fc07f1d66e
7 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,3 @@
build
node_modules
.wrangler

View File

@ -0,0 +1,12 @@
.PHONY: dev
dev:
wrangler dev --test-scheduled
.PHONY: build
build:
go run ../../cmd/workers-assets-gen
tinygo build -o ./build/app.wasm -target wasm -no-debug ./...
.PHONY: deploy
deploy:
wrangler deploy

View File

@ -0,0 +1,29 @@
# multiple-handlers
* This example shows how to use multiple handlers in a single worker.
## Development
### Requirements
This project requires these tools to be installed globally.
* wrangler
* tinygo
### Commands
```
make dev # run dev server
make build # build Go Wasm binary
make deploy # deploy worker
```
#### Testing cron schedule
* With curl command below, you can test the cron schedule.
- see: https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/#background
```
curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*"
```

View File

@ -0,0 +1,7 @@
module github.com/syumai/workers/_examples/multiple-handlers
go 1.21.3
require github.com/syumai/workers v0.0.0
replace github.com/syumai/workers => ../../

View File

View File

@ -0,0 +1,38 @@
package main
import (
"context"
"fmt"
"net/http"
"github.com/syumai/workers"
"github.com/syumai/workers/cloudflare/cron"
)
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, "Hello, world!")
})
task := func(ctx context.Context) error {
e, err := cron.NewEvent(ctx)
if err != nil {
return err
}
fmt.Println(e.ScheduledTime.Unix())
return nil
}
// set up the worker
workers.ServeNonBlock(handler)
cron.ScheduleTaskNonBlock(task)
// send a ready signal to the runtime
workers.Ready()
// block until the handler or task is done
select {
case <-workers.Done():
case <-cron.Done():
}
}

View File

@ -0,0 +1,10 @@
name = "multiple-handlers"
main = "./build/worker.mjs"
compatibility_date = "2023-02-24"
workers_dev = false
[triggers]
crons = ["* * * * *"]
[build]
command = "make build"