From ed33cd9690449a5fc633d88262038a8906ac0d5f Mon Sep 17 00:00:00 2001 From: labulakalia Date: Mon, 4 May 2026 17:33:08 +0800 Subject: [PATCH] fix fetch failed on env global and service-binding --- cloudflare/fetch/bind.go | 23 +++++++++++++++-------- internal/jshttp/request.go | 3 +-- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/cloudflare/fetch/bind.go b/cloudflare/fetch/bind.go index 5009b80..610cbe5 100644 --- a/cloudflare/fetch/bind.go +++ b/cloudflare/fetch/bind.go @@ -15,14 +15,21 @@ func fetch(namespace js.Value, req *http.Request, init *RequestInit) (*http.Resp if namespace.IsUndefined() { return nil, errors.New("fetch function not found") } - promise := namespace.Call("fetch", - // The Request object to fetch. - // Docs: https://developers.cloudflare.com/workers/runtime-apis/request - jshttp.ToJSRequest(req), - // The content of the request. - // Docs: https://developers.cloudflare.com/workers/runtime-apis/request#requestinit - init.ToJS(), - ) + var promise js.Value + // The Request object to fetch. + // Docs: https://developers.cloudflare.com/workers/runtime-apis/request + var reqValue = jshttp.ToJSRequest(req) + // The content of the request. + // Docs: https://developers.cloudflare.com/workers/runtime-apis/request#requestinit + var initValue = init.ToJS() + if namespace.Equal(js.Global()) { + // global fetch + fetchFunc := namespace.Get("fetch") + promise = fetchFunc.Invoke(reqValue, initValue) + } else { + // service-binding + promise = namespace.Call("fetch", reqValue, initValue) + } jsRes, err := jsutil.AwaitPromise(promise) if err != nil { diff --git a/internal/jshttp/request.go b/internal/jshttp/request.go index a0c7797..ca34bcb 100644 --- a/internal/jshttp/request.go +++ b/internal/jshttp/request.go @@ -1,7 +1,6 @@ package jshttp import ( - "bytes" "io" "net/http" "net/url" @@ -16,7 +15,7 @@ import ( // - ReadableStream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream func ToBody(streamOrNull js.Value) io.ReadCloser { if streamOrNull.IsNull() { - return io.NopCloser(bytes.NewReader([]byte{})) + return nil } return jsutil.ConvertReadableStreamToReadCloser(streamOrNull) }