add worker-tinygo template

This commit is contained in:
syumai 2023-04-30 11:52:54 +09:00
parent ac05c2a9ae
commit 8978b3b2b0
5 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1 @@
build

View File

@ -0,0 +1,12 @@
.PHONY: dev
dev:
wrangler dev
.PHONY: build
build:
go run github.com/syumai/workers/cmd/workers-assets-gen@latest
tinygo build -o ./build/app.wasm -target wasm ./...
.PHONY: publish
publish:
wrangler publish

View File

@ -0,0 +1,53 @@
# worker-template-tinygo
- A template for starting a Cloudflare Worker project with tinygo.
- This template uses [`workers`](https://github.com/syumai/workers) package to run an HTTP server.
## Usage
- `main.go` includes simple HTTP server implementation. Feel free to edit this code and implement your own HTTP server.
## Requirements
- Node.js
- [wrangler](https://developers.cloudflare.com/workers/wrangler/)
- just run `npm install -g wrangler`
- tinygo
## Getting Started
```
$ wrangler generate my-app syumai/workers/_templates/cloudflare/worker-tinygo
$ cd my-app
$ go mod init
$ go mod tidy
$ make dev # start running dev server
$ curl http://localhost:8787/hello
Hello!
```
- To change worker name, please edit `name` property in `wrangler.toml`.
## Development
### Commands
```
make dev # run dev server
make build # build Go Wasm binary
make publish # publish worker
```
### Testing dev server
- Just send HTTP request using some tools like curl.
```
$ curl http://localhost:8787/hello
Hello!
```
```
$ curl -X POST -d "test message" http://localhost:8787/echo
test message
```

View File

@ -0,0 +1,19 @@
package main
import (
"io"
"net/http"
"github.com/syumai/workers"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
msg := "Hello!"
w.Write([]byte(msg))
})
http.HandleFunc("/echo", func(w http.ResponseWriter, req *http.Request) {
io.Copy(w, req.Body)
})
workers.Serve(nil) // use http.DefaultServeMux
}

View File

@ -0,0 +1,9 @@
name = "tinygo-worker"
main = "./build/worker.mjs"
compatibility_date = "2022-05-13"
compatibility_flags = [
"streams_enable_constructors"
]
[build]
command = "make build"