mirror of
https://github.com/syumai/workers.git
synced 2025-03-10 17:29:11 +00:00
R: refactor with bind func
This commit is contained in:
parent
7926558e38
commit
9e97a4a812
33
cloudflare/fetch/bind.go
Normal file
33
cloudflare/fetch/bind.go
Normal file
@ -0,0 +1,33 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"syscall/js"
|
||||
|
||||
"github.com/syumai/workers/internal/jshttp"
|
||||
"github.com/syumai/workers/internal/jsutil"
|
||||
)
|
||||
|
||||
// fetch is a function that reproduces cloudflare fetch.
|
||||
// Docs: https://developers.cloudflare.com/workers/runtime-apis/fetch/
|
||||
func fetch(namespace js.Value, req *http.Request /* TO DO: options here */) (*http.Response, error) {
|
||||
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
|
||||
jsutil.NewObject(),
|
||||
)
|
||||
jsRes, err := jsutil.AwaitPromise(promise)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return jshttp.ToResponse(jsRes)
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/syumai/workers/internal/jshttp"
|
||||
"github.com/syumai/workers/internal/jsutil"
|
||||
)
|
||||
|
||||
// Do sends an HTTP request and returns an HTTP response
|
||||
func (c *Client) Do(req *Request) (*http.Response, error) {
|
||||
jsReq := jshttp.ToJSRequest(req.Request)
|
||||
|
||||
init := jsutil.NewObject()
|
||||
promise := c.namespace.Call("fetch", jsReq, init)
|
||||
jsRes, err := jsutil.AwaitPromise(promise)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return jshttp.ToResponse(jsRes)
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user