Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init Go instance on request #91

Merged
merged 1 commit into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/workers-assets-gen/assets/common/shim.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import "./wasm_exec.js";
import { connect } from 'cloudflare:sockets';

const go = new Go();

let mod;

globalThis.tryCatch = (fn) => {
Expand All @@ -22,6 +20,8 @@ export function init(m) {
}

async function run(ctx) {
const go = new Go();

let ready;
const readyPromise = new Promise((resolve) => {
ready = resolve;
Expand Down
20 changes: 17 additions & 3 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import (
"github.com/syumai/workers/internal/runtimecontext"
)

var httpHandler http.Handler
var (
httpHandler http.Handler
closeCh = make(chan struct{})
)

func init() {
var handleRequestCallback js.Func
Expand Down Expand Up @@ -40,6 +43,15 @@ func init() {
jsutil.Binding.Set("handleRequest", handleRequestCallback)
}

type appCloser struct {
io.ReadCloser
}

func (c *appCloser) Close() error {
defer close(closeCh)
return c.ReadCloser.Close()
}

// handleRequest accepts a Request object and returns Response object.
func handleRequest(reqObj js.Value, runtimeCtxObj js.Value) (js.Value, error) {
if httpHandler == nil {
Expand All @@ -55,7 +67,7 @@ func handleRequest(reqObj js.Value, runtimeCtxObj js.Value) (js.Value, error) {
w := &jshttp.ResponseWriter{
HeaderValue: http.Header{},
StatusCode: http.StatusOK,
Reader: reader,
Reader: &appCloser{reader},
Writer: writer,
ReadyCh: make(chan struct{}),
}
Expand All @@ -79,5 +91,7 @@ func Serve(handler http.Handler) {
}
httpHandler = handler
ready()
select {}
select {
case <-closeCh:
}
}
2 changes: 1 addition & 1 deletion internal/jshttp/responsewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
type ResponseWriter struct {
HeaderValue http.Header
StatusCode int
Reader *io.PipeReader
Reader io.ReadCloser
Writer *io.PipeWriter
ReadyCh chan struct{}
Once sync.Once
Expand Down
Loading