mirror of
https://github.com/imjasonh/gocf
synced 2026-07-07 02:22:17 +00:00
86 lines
1.7 KiB
JavaScript
86 lines
1.7 KiB
JavaScript
import "./wasm_exec.js";
|
|
import { createRuntimeContext, loadModule } from "./runtime.mjs";
|
|
|
|
let mod;
|
|
|
|
globalThis.tryCatch = (fn) => {
|
|
try {
|
|
return {
|
|
result: fn(),
|
|
};
|
|
} catch (e) {
|
|
return {
|
|
error: e,
|
|
};
|
|
}
|
|
};
|
|
|
|
async function run(ctx) {
|
|
if (mod === undefined) {
|
|
mod = await loadModule();
|
|
}
|
|
const go = new Go();
|
|
|
|
let ready;
|
|
const readyPromise = new Promise((resolve) => {
|
|
ready = resolve;
|
|
});
|
|
const instance = new WebAssembly.Instance(mod, {
|
|
...go.importObject,
|
|
workers: {
|
|
ready: () => {
|
|
ready();
|
|
},
|
|
},
|
|
});
|
|
go.run(instance, ctx);
|
|
await readyPromise;
|
|
}
|
|
|
|
async function fetch(req, env, ctx) {
|
|
const binding = {};
|
|
await run(createRuntimeContext({ env, ctx, binding }));
|
|
return binding.handleRequest(req);
|
|
}
|
|
|
|
async function scheduled(event, env, ctx) {
|
|
const binding = {};
|
|
await run(createRuntimeContext({ env, ctx, binding }));
|
|
return binding.runScheduler(event);
|
|
}
|
|
|
|
async function queue(batch, env, ctx) {
|
|
const binding = {};
|
|
await run(createRuntimeContext({ env, ctx, binding }));
|
|
return binding.handleQueueMessageBatch(batch);
|
|
}
|
|
|
|
// Counter Durable Object
|
|
export class Counter {
|
|
constructor(state, env) {
|
|
this.state = state;
|
|
this.env = env;
|
|
}
|
|
|
|
async fetch(request) {
|
|
// Get the current count from storage
|
|
let count = (await this.state.storage.get("count")) || 0;
|
|
|
|
// Increment the count
|
|
count++;
|
|
|
|
// Store the new count
|
|
await this.state.storage.put("count", count);
|
|
|
|
// Return the count
|
|
return new Response(`Count: ${count}`, {
|
|
headers: { "Content-Type": "text/plain" },
|
|
});
|
|
}
|
|
}
|
|
|
|
export default {
|
|
fetch,
|
|
scheduled,
|
|
queue,
|
|
};
|