F: add fetch (wip)

This commit is contained in:
aki-0421 2023-04-02 20:12:19 +09:00
parent 3dcf908475
commit eb6c550c8b
No known key found for this signature in database
GPG Key ID: 64A8CF6D437D166A
3 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1,24 @@
package fetch
import (
"net/http"
"syscall/js"
"github.com/syumai/workers/internal/jsutil"
)
// Client is an HTTP client.
type Client struct {
*http.Client
// namespace - Objects that Fetch API belongs to. Default is Global
namespace js.Value
}
// NewClient returns new Client
func NewClient() *Client {
return &Client{
Client: &http.Client{},
namespace: jsutil.Global,
}
}

22
cloudflare/fetch/http.go Normal file
View File

@ -0,0 +1,22 @@
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("fetch2", jsReq, init)
jsRes, err := jsutil.AwaitPromise(promise)
if err != nil {
return nil, err
}
return jshttp.ToResponse(jsRes)
}

View File

@ -0,0 +1,25 @@
package fetch
import (
"context"
"io"
"net/http"
)
// Request represents an HTTP request and is part of the Fetch API.
// Docs: https://developers.cloudflare.com/workers/runtime-apis/request/
type Request struct {
*http.Request
}
// NewRequest returns new Request given a method, URL, and optional body
func NewRequest(ctx context.Context, method string, url string, body io.Reader) (*Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
return &Request{
Request: req,
}, nil
}