2023-04-02 20:12:19 +09:00
|
|
|
package fetch
|
|
|
|
|
|
|
|
import (
|
2023-04-11 21:33:52 +09:00
|
|
|
"net/http"
|
2023-04-02 20:12:19 +09:00
|
|
|
"syscall/js"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Client is an HTTP client.
|
|
|
|
type Client struct {
|
|
|
|
// namespace - Objects that Fetch API belongs to. Default is Global
|
|
|
|
namespace js.Value
|
|
|
|
}
|
|
|
|
|
2023-04-09 09:23:07 +09:00
|
|
|
// applyOptions applies client options.
|
|
|
|
func (c *Client) applyOptions(opts []ClientOption) {
|
|
|
|
for _, opt := range opts {
|
|
|
|
opt(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-11 21:33:52 +09:00
|
|
|
// HTTPClient returns *http.Client.
|
2023-05-28 13:04:35 +09:00
|
|
|
func (c *Client) HTTPClient(redirect RedirectMode) *http.Client {
|
2023-04-11 21:33:52 +09:00
|
|
|
return &http.Client{
|
|
|
|
Transport: &transport{
|
|
|
|
namespace: c.namespace,
|
2023-05-28 13:04:35 +09:00
|
|
|
redirect: redirect,
|
2023-04-11 21:33:52 +09:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-09 09:23:07 +09:00
|
|
|
// ClientOption is a type that represents an optional function.
|
|
|
|
type ClientOption func(*Client)
|
|
|
|
|
|
|
|
// WithBinding changes the objects that Fetch API belongs to.
|
|
|
|
// This is useful for service bindings, mTLS, etc.
|
|
|
|
func WithBinding(bind js.Value) ClientOption {
|
|
|
|
return func(c *Client) {
|
|
|
|
c.namespace = bind
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-02 20:12:19 +09:00
|
|
|
// NewClient returns new Client
|
2023-04-09 09:23:07 +09:00
|
|
|
func NewClient(opts ...ClientOption) *Client {
|
|
|
|
c := &Client{
|
2024-01-04 22:45:03 +09:00
|
|
|
namespace: js.Global(),
|
2023-04-02 20:12:19 +09:00
|
|
|
}
|
2023-04-09 09:23:07 +09:00
|
|
|
c.applyOptions(opts)
|
|
|
|
|
|
|
|
return c
|
2023-04-02 20:12:19 +09:00
|
|
|
}
|