Skip to content

Instantly share code, notes, and snippets.

@MstrVLT
Created February 28, 2025 20:26
Show Gist options
  • Save MstrVLT/92b033f2ab590bf9b9e04c75893b53d7 to your computer and use it in GitHub Desktop.
Save MstrVLT/92b033f2ab590bf9b9e04c75893b53d7 to your computer and use it in GitHub Desktop.
Go (GOOS=js GOARCH=wasm) + Vite
package main
//go:wasmexport add
func add(a int32, b int32) int32 {
return a + b
}
func main() {}
// GOOS=js GOARCH=wasm go build -o main.wasm
import goWorker from "@/worker?worker"; // https://vite.dev/guide/features.html#import-with-query-suffixes
let worker = null
const initWorker = () => {
if (worker !== null) return
worker = new goWorker();
worker.onmessage = ({ data }) => {
let { action, payload } = data;
switch (action) {
case "ready":
console.log("worker ready", data);
worker.postMessage({ action: "call", payload: null });
break;
case "result":
console.log("result", action, payload);
break;
default:
console.log("unknown action", action, payload);
break;
}
};
}
initWorker()
import wasmUrl from "./main.wasm?url"; // https://vite.dev/guide/features.html#accessing-the-webassembly-module
import "./wasm_exec.js"; // wasm_exec.js located in lib/wasm/wasm_exec.js just copy to project
const responsePromise = fetch(wasmUrl);
const go = new Go();
let exports;
WebAssembly.instantiateStreaming(responsePromise, go.importObject)
.then(async ({ instance }) => {
exports = instance.exports;
await go.run(instance);
postMessage({ action: "ready", payload: null });
})
.catch((err) => {
console.error("Worker failed to load module: ", err);
});
onmessage = ({ data }) => {
const { action, payload } = data;
switch (action) {
case "call":
const res = exports.add(3,5);
postMessage({ action: "result", payload: res });
break;
default:
console.log("unknown action", action);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment