mirror of
https://github.com/syumai/workers.git
synced 2025-03-11 09:49:12 +00:00
F: add fetch (wip)
This commit is contained in:
parent
3dcf908475
commit
eb6c550c8b
24
cloudflare/fetch/client.go
Normal file
24
cloudflare/fetch/client.go
Normal 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
22
cloudflare/fetch/http.go
Normal 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)
|
||||||
|
}
|
25
cloudflare/fetch/request.go
Normal file
25
cloudflare/fetch/request.go
Normal 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
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user