Readme

Compile and Upload Tinygo WASM to Val Town Using Deno

Make a Go program like so:

package main

import (
	"fmt"
	"net/http"
	gotown "github.com/maxmcd/go-town"
)

func main() {
	gotown.ListenAndServe(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello World")
	}))
}

Make sure you have tinygo (and optionally wasm-strip) installed. Then run this command with Deno to invoke this script:

 deno run --allow-net --allow-run --allow-read \
    "https://esm.town/v/maxm/compileAndUploadTinygoWasm?v=58"

That will print out the following:

Running tinygo build -o main.wasm -target=wasi .
Compliation complete
Running wasm-strip main.wasm

Copy the following into a val town HTTP val:

import { wasmHandler } from "https://esm.town/v/maxm/tinygoHttp";
const resp = await fetch("https://maxm-wasmBlobHost.web.val.run/jpxqvyy5tphiwehzklmioklpkpz4gpzs.wasm");
const handler = await wasmHandler(new Uint8Array(await resp.arrayBuffer()));
export default async function(req: Request): Promise<Response> {
  return handler(req);
}

Copy that into a Val and you have a working Go http handler! View that example here: https://www.val.town/v/maxm/crimsonMacaw

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
await (async () => {
const command = "tinygo";
const args = [
"build",
"-o",
"main.wasm",
"-target=wasi",
".",
];
console.log("Running", [command, ...args].join(" "));
const cmd = new Deno.Command(command, {
args,
stdout: "inherit",
stderr: "inherit",
});
const { code } = await cmd.output();
console.assert(code === 0);
console.log("Compliation complete");
})();
await (async () => {
const command = "wasm-strip";
const args = [
"main.wasm",
];
console.log("Running", [command, ...args].join(" "));
const cmd = new Deno.Command(command, {
args,
stdout: "inherit",
stderr: "inherit",
});
try {
const { code } = await cmd.output();
console.assert(code === 0);
} catch (e) {
console.log(e);
console.log("wasm-strip failed, install with `brew install wabt`?");
console.log("Continuing to upload without stripping");
}
})();
let resp = await fetch("https://maxm-wasmBlobHost.web.val.run", {
method: "POST",
headers: {
"Content-Type": "application/wasm",
},
body: Deno.readFileSync("main.wasm"),
});
console.assert(resp.status === 200);
const { url } = await resp.json();
console.log(`
Copy the following into a val town HTTP val:
import { wasmHandler } from "https://esm.town/v/maxm/tinygoHttp";
const resp = await fetch("${url}");
const handler = await wasmHandler(new Uint8Array(await resp.arrayBuffer()));
export default async function(req: Request): Promise<Response> {
return handler(req);
}`);
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v59
May 24, 2024