jsFetch

package module
v1.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2025 License: LGPL-3.0 Imports: 17 Imported by: 0

README

jsFetch

Go library to bridge net/http and the JS Fetch API, without actually importing net/http. Made using the jsStreams library.

Go Report Card Go Reference

The API is exactly the same as net/http.

Important note

It is common for it to return the error "Failed to fetch" with the error ERR_H2_OR_QUIC_REQUIRED in Chromium-based browsers. To fix this, you are able to modify the request to set request.DisableStreamedClient to true. This is because Chromium has a method of upload ReadableStream data that requires HTTP/2 or QUIC to be enabled for security reasons.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultClient = Fetch

DefaultClient is an alias for Fetch.

View Source
var Fetch = &Client{
	Transport: FetchRoundTripper,
	Timeout:   20 * time.Second,
}

Fetch is a fetch client. It is used to make requests. It wraps around JS fetch.

Functions

func CanonicalHeaderKey

func CanonicalHeaderKey(key string) string

Types

type Client

type Client struct {
	// Transport specifies the mechanism by which individual requests are made.
	// If nil, FetchRoundTripper is used.
	Transport RoundTripper

	// Jar does nothing, but it is required for compatibility with the Go standard library.
	Jar CookieJar

	// Timeout specifies a time limit for requests made by this Client.
	Timeout time.Duration
}

Client is a fetch client. It is used to make requests.

func (*Client) Do

func (c *Client) Do(req *Request) (resp *Response, err error)

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

type Cookie struct {
	Name        string
	Value       string
	Quoted      bool
	Path        string
	Domain      string
	Expires     time.Time
	RawExpires  string
	MaxAge      int
	Secure      bool
	HttpOnly    bool
	SameSite    SameSite
	Partitioned bool
	Raw         string
	Unparsed    []string
}

Cookie does nothing, but it is required for compatibility with the Go standard library.

type CookieJar

type CookieJar interface {
	SetCookies(u *url.URL, cookies []*Cookie)
	Cookies(u *url.URL) []*Cookie
}

CookieJar does nothing, but it is required for compatibility with the Go standard library.

type Header map[string]string

func (Header) Add

func (h Header) Add(key, value string)

func (Header) Clone

func (h Header) Clone() (newHeader Header)

func (Header) Del

func (h Header) Del(key string)

func (Header) Get

func (h Header) Get(key string) (value string)

func (Header) Has

func (h Header) Has(key string) (has bool)

func (Header) Set

func (h Header) Set(key, value string)

func (Header) Values

func (h Header) Values() (values []string)

func (Header) Write

func (h Header) Write(w io.Writer) error

func (Header) WriteSubset

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

type Request

type Request struct {
	// DisableStreamedClient specifies whether to use a streamed client body.
	// This is set to false by default, but has checks to make sure it's running on a supported browser.
	// HTTP/2 or QUIC to be enabled when using V8, which is not always the case, particularly on
	// older servers or test servers.
	//
	// If DisableStreamedClientChecks is set to false, the client will first attempt to detect if
	// the server supports HTTP/2 or QUIC and if you are running a supported JavaScript engine.
	// Supported browser engines include:
	// - V8 (Chrome, Edge, Opera)
	// Unsupported browser engines include:
	// - SpiderMonkey (Firefox)
	// - JavaScriptCore (Safari)
	// - Chakra (Internet Explorer)
	// - KJS (Konqueror)
	// - Presto (Opera Mini and ancient versions of Opera)
	// Data from https://caniuse.com/mdn-api_request_request_request_body_readablestream
	// TL;DR If it's chromium it'll work.
	DisableStreamedClient bool

	// DisableStreamedClientChecks specifies whether to disable checks for streamed clients.
	// It does nothing if UseStreamedClient is set to false.
	// Having it set to false may add another HEAD request to the server, which may be undesirable.
	// Also, forcing it on may be useful if SpiderMonkey one day supports streamed clients bodies.
	DisableStreamedClientChecks bool

	// Method specifies the HTTP method (GET, POST, PUT, etc.).
	Method string

	// URL specifies either the URL to fetch as a string, or a URL object.
	URL *url.URL

	// Headers is a Headers object, allowing you to set request headers.
	Header Header

	// Body is an optional body to be sent with the request.
	Body io.ReadCloser

	// GetBody is an optional function that returns a ReadCloser for the body.
	GetBody func() (io.ReadCloser, error)

	// ContentLength is the length of the body. It is mostly superseded by the Content-Length header.
	ContentLength int64

	// Proto, ProtoMajor, ProtoMinor specify the HTTP protocol version.
	// This is useless, as fetch does not allow you to specify the protocol version.
	Proto      string
	ProtoMajor int
	ProtoMinor int

	// Close indicates whether to close the connection after the request.
	// This is useless, as fetch does not allow you to specify whether to close the connection and instead forces you to use a WebSocket.
	Close bool

	// Host specifies the host to perform the request to.
	// This is useless, as it only makes sense in the context of the Host or :authority headers, both of which are filled-in automatically by fetch.
	Host string

	// TransferEncoding specifies the transfer encodings to be used.
	// This is useless, as since we always use a stream, the transfer encoding is always chunked.
	TransferEncoding []string

	// Form, PostForm, and MultipartForm specify the parsed form data.
	// This is useless, because even the Go standard library does not use it.
	// Use Body instead.
	Form          url.Values
	PostForm      url.Values
	MultipartForm *url.Values

	// Trailer specifies additional headers that are sent after the request body.
	// This is useless, as fetch does not allow you to specify trailers.
	// Not to mention, nothing supports trailers.
	Trailer Header

	// RemoteAddr and RequestURI specify the remote address and Request-URI for the request.
	// This is useless, as fetch does not allow you to specify the remote address, and you should use URL instead of RequestURI.
	RemoteAddr string
	RequestURI string

	// TLS allows you to specify the TLS connection state.
	// This is useless, as fetch does not allow you to specify the TLS connection state.
	TLS *tls.ConnectionState

	// Cancel is an optional channel that can be used to cancel the request.
	// This isn't even in the Go standard library anymore.
	Cancel <-chan struct{}

	// Response is the response that caused this request to be created, usually in a redirect.
	// This is useless, as fetch follows redirects automatically.
	Response *Response

	// Pattern is the pattern that was matched for this request.
	// This is useless, as fetch does not support pattern matching.
	Pattern string
}

func NewRequest

func NewRequest(method, uri string, body io.Reader) (request *Request, err error)

func (*Request) AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie does nothing, but it is required for compatibility with the Go standard library.

func (*Request) BasicAuth

func (r *Request) BasicAuth() (username, password string, ok bool)

BasicAuth does nothing, but it is required for compatibility with the Go standard library.

func (*Request) Clone

func (r *Request) Clone() (newRequest *Request)

func (*Request) Context

func (r *Request) Context() context.Context

Context does nothing, but it is required for compatibility with the Go standard library.

func (*Request) Cookie

func (r *Request) Cookie(name string) (*Cookie, error)

Cookie does nothing, but it is required for compatibility with the Go standard library.

func (*Request) Cookies

func (r *Request) Cookies() []*Cookie

Cookies does nothing, but it is required for compatibility with the Go standard library.

func (*Request) CookiesNamed

func (r *Request) CookiesNamed(name string) []*Cookie

CookiesNamed does nothing, but it is required for compatibility with the Go standard library.

func (*Request) FormFile

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile does nothing, but it is required for compatibility with the Go standard library.

func (*Request) FormValue

func (r *Request) FormValue(key string) string

FormValue does nothing, but it is required for compatibility with the Go standard library.

func (*Request) MultipartReader

func (r *Request) MultipartReader() (*multipart.Reader, error)

MultipartReader does nothing, but it is required for compatibility with the Go standard library.

func (*Request) ParseForm

func (r *Request) ParseForm() error

ParseForm does nothing, but it is required for compatibility with the Go standard library.

func (*Request) ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm does nothing, but it is required for compatibility with the Go standard library.

func (*Request) PostFormValue

func (r *Request) PostFormValue(key string) string

PostFormValue does nothing, but it is required for compatibility with the Go standard library.

func (*Request) ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast does nothing, but it is required for compatibility with the Go standard library.

func (*Request) Referer

func (r *Request) Referer() string

Referer returns the value of the Referer header.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string)

SetBasicAuth does nothing, but it is required for compatibility with the Go standard library.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the value of the User-Agent header.

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext does nothing, but it is required for compatibility with the Go standard library.

func (*Request) Write

func (r *Request) Write(w io.Writer) error

Write writes an HTTP/1.1 request, which is the header and body, in wire format. It is not yet implemented (and probably never will be, because after all, why would you need to write an HTTP request in wire format?).

func (*Request) WriteProxy

func (r *Request) WriteProxy(w io.Writer) error

WriteProxy does nothing, but it is required for compatibility with the Go standard library.

type Response

type Response struct {
	// Status specifies the HTTP status.
	// It will be an empty string if using HTTP/2.
	Status string

	// StatusCode specifies the HTTP status code.
	StatusCode int

	// Header specifies the response headers.
	Header Header

	// Body is the response body.
	Body io.ReadCloser

	// TransferEncoding specifies the transfer encodings that have been applied to the response.
	TransferEncoding []string

	// ContentLength specifies the length of the body.
	// It is mostly superseded by the Content-Length header.
	// A value of -1 indicates that the length is unknown.
	ContentLength int64

	// Request is the request that was made to get this response.
	Request *Request

	// Proto, ProtoMajor, ProtoMinor specify the HTTP protocol version.
	// This is useless, as fetch does not allow you to specify the protocol version.
	Proto      string
	ProtoMajor int
	ProtoMinor int

	// Close indicates whether to close the connection after the request.
	// This is useless, as fetch does not allow you to specify whether to close the connection and instead forces you to use a WebSocket.
	Close bool

	// Uncompressed specifies whether the response is uncompressed.
	// This is useless, as fetch does not allow you to specify whether the response is uncompressed.
	Uncompressed bool

	// Trailer specifies additional headers that are sent after the request body.
	// This is useless, as fetch does not allow you to specify trailers.
	// Not to mention, nothing supports trailers.
	Trailer Header

	// TLS allows you to specify the TLS connection state.
	// This is useless, as fetch does not allow you to specify the TLS connection state.
	TLS *tls.ConnectionState
}

func Get

func Get(url string) (response *Response, err error)

func Post

func Post(url string, contentType string, body io.Reader) (response *Response, err error)

func PostForm

func PostForm(url string, data url.Values) (response *Response, err error)

func (*Response) Cookies

func (r *Response) Cookies() []*Cookie

Cookies does nothing, but it is required for compatibility with the Go standard library.

func (*Response) Location

func (r *Response) Location() (string, error)

Location returns the location header (if present).

func (*Response) ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast does nothing, but it is required for compatibility with the Go standard library.

func (*Response) Write

func (r *Response) Write(w io.Writer) error

Write writes an HTTP/1.1 response, which is the header and body, in wire format. It is not yet implemented (and probably never will be, because after all, why would you need to write an HTTP response in wire format?).

type RoundTripper

type RoundTripper interface {
	// RoundTrip executes a single HTTP transaction, returning a Response for the provided Request.
	// In the context of fetch, it will automatically follow redirects.
	RoundTrip(*Request) (*Response, error)
}

RoundTripper is an interface representing the ability to execute a single HTTP transaction.

var FetchRoundTripper RoundTripper = &Transport{}

FetchRoundTripper is a wrapper around the fetch API. It is used to make requests. It is the default RoundTripper used for this subset of net/http.

type SameSite

type SameSite int

SameSite does nothing, but it is required for compatibility with the Go standard library.

type Transport

type Transport struct {
	// Proxy specifies a function to return a proxy for a given Request.
	// It is ignored in fetch.
	Proxy func(*Request) (*url.URL, error)

	// OnProxyError specifies a function to handle errors that occur while fetching a proxy.
	// It is ignored in fetch.
	OnProxyError func(*Request, *url.URL, error)

	// DialContext specifies the dial function for creating unencrypted TCP connections.
	// It is ignored in fetch.
	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// Dial specifies the dial function for creating unencrypted TCP connections.
	// It is ignored in fetch.
	Dial func(network, addr string) (net.Conn, error)

	// DialTLSContext specifies the dial function for creating TLS connections.
	// It is ignored in fetch.
	DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// DialTLS specifies the dial function for creating TLS connections.
	// It is ignored in fetch.
	DialTLS func(network, addr string) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with tls.Client.
	// It is ignored in fetch.
	TLSClientConfig *tls.Config

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to wait for a TLS handshake.
	// It is ignored in fetch.
	TLSHandshakeTimeout time.Duration

	// DisableKeepAlives specifies whether to disable keep-alive connections.
	// It is ignored in fetch.
	DisableKeepAlives bool

	// DisableCompression specifies whether to disable compression.
	// It is ignored in fetch.
	DisableCompression bool

	// MaxIdleConns specifies the maximum number of idle (keep-alive) connections to keep.
	// It is ignored in fetch.
	MaxIdleConns int

	// MaxIdleConnsPerHost specifies the maximum number of idle (keep-alive) connections to keep per host.
	// It is ignored in fetch.
	MaxIdleConnsPerHost int

	// IdleConnTimeout specifies the maximum amount of time an idle (keep-alive) connection will remain idle before closing itself.
	// It is ignored in fetch.
	IdleConnTimeout time.Duration

	// ResponseHeaderTimeout specifies the maximum amount of time to wait for a response header.
	// It is ignored in fetch.
	ResponseHeaderTimeout time.Duration

	// ExpectContinueTimeout specifies the maximum amount of time to wait for a 100-continue response.
	// It is ignored in fetch.
	ExpectContinueTimeout time.Duration

	// TLSNextProto specifies a function to upgrade the connection to a different protocol.
	// It is ignored in fetch.
	TLSNextProto map[string]func(authority string, c net.Conn) RoundTripper

	// ProxyConnectHeader specifies the headers to send to proxies during CONNECT requests.
	// It is ignored in fetch.
	ProxyConnectHeader Header

	// MaxResponseHeaderBytes specifies the maximum number of bytes to read from the server's response headers.
	// It is ignored in fetch.
	MaxResponseHeaderBytes int

	// WriteBufferSize specifies the size of the write buffer.
	// It is ignored in fetch.
	WriteBufferSize int

	// ReadBufferSize specifies the size of the read buffer.
	// It is ignored in fetch.
	ReadBufferSize int

	// ForceAttemptHTTP2 specifies whether to force an attempt to use HTTP/2.
	// It is ignored in fetch.
	ForceAttemptHTTP2 bool
}

Transport is here only for compatibility with the Go standard library. All fields are ignored in fetch.

func (*Transport) Clone

func (t *Transport) Clone() (newTransport *Transport)

Clone returns a copy of the Transport.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any idle connections. This does nothing in fetch.

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(protocol string, rt RoundTripper)

RegisterProtocol registers a new protocol with a custom RoundTripper. This does nothing in fetch.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *Request) (resp *Response, err error)

RoundTrip executes a single HTTP transaction, returning a Response for the provided Request. In the context of fetch, it will automatically follow redirects. This implementation is a wrapper around the fetch API.

Directories

Path Synopsis
tests

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL