fetch

package
v1.25.2 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2024 License: MIT, MIT Imports: 0 Imported by: 0

README

Fetch

Wrapper for the Fetch API

Upstream

Upstream: https://github.com/marwan-at-work/wasm-fetch

Forked here. This sub-directory (only) is licensed MIT.

Documentation

Overview

Package fetch is a js fetch wrapper that avoids importing net/http.

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
resp, err := fetch.Fetch("/some/api/call", &fetch.Opts{
	Body:   strings.NewReader(`{"one": "two"}`),
	Method: fetch.MethodPost,
	Signal: ctx,
})

Index

Constants

View Source
const (
	CacheDefault      = "default"
	CacheNoStore      = "no-store"
	CacheReload       = "reload"
	CacheNone         = "no-cache"
	CacheForce        = "force-cache"
	CacheOnlyIfCached = "only-if-cached"
)

cache enums

View Source
const (
	CredentialsOmit       = "omit"
	CredentialsSameOrigin = "same-origin"
	CredentialsInclude    = "include"
)

credentials enums

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

Common HTTP methods.

Unless otherwise noted, these are defined in RFC 7231 section 4.3.

View Source
const (
	ModeSameOrigin = "same-origin"
	ModeNoCORS     = "no-cors"
	ModeCORS       = "cors"
	ModeNavigate   = "navigate"
)

Mode enums

View Source
const (
	RedirectFollow = "follow"
	RedirectError  = "error"
	RedirectManual = "manual"
)

Redirect enums

View Source
const (
	ReferrerNone   = "no-referrer"
	ReferrerClient = "client"
)

Referrer enums

View Source
const (
	ReferrerPolicyNone        = "no-referrer"
	ReferrerPolicyNoDowngrade = "no-referrer-when-downgrade"
	ReferrerPolicyOrigin      = "origin"
	ReferrerPolicyCrossOrigin = "origin-when-cross-origin"
	ReferrerPolicyUnsafeURL   = "unsafe-url"
)

ReferrerPolicy enums

Variables

This section is empty.

Functions

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". If s contains a space or invalid header field bytes, it is returned without modifications.

Types

type Header map[string][]string

A Header represents the key-value pairs in an HTTP header.

func (Header) Add

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

Add adds the key, value pair to the header. It appends to any existing values associated with key.

func (Header) Clone

func (h Header) Clone() Header

Clone returns a deep copy of the header.

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key.

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. If there are no values associated with the key, Get returns "". To access multiple values of a key, or to use non-canonical keys, access the map directly.

func (Header) Set

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

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

func (Header) Write

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

Write writes a header in wire format.

func (Header) WriteSubset

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

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written.

type Opts

type Opts struct {
	// CommonOpts are the common Fetch options.
	CommonOpts

	// Method specifies the HTTP method (GET, POST, PUT, etc.).
	// For client requests, an empty string means GET.
	// constants are copied from net/http to avoid import
	Method string

	// Header contains the request header fields.
	//
	// Example:
	//
	//	Host: example.com
	//	accept-encoding: gzip, deflate
	//	Accept-Language: en-us
	//	fOO: Bar
	//	foo: two
	//
	// then
	//
	//	Header = map[string][]string{
	//		"Accept-Encoding": {"gzip, deflate"},
	//		"Accept-Language": {"en-us"},
	//		"Foo": {"Bar", "two"},
	//	}
	//
	// HTTP defines that header names are case-insensitive. The
	// request parser implements this by using CanonicalHeaderKey,
	// making the first character and any characters following a
	// hyphen uppercase and the rest lowercase.
	//
	// Certain headers such as Content-Length and Connection are automatically
	// written when needed and values in Header may be ignored.
	Header Header

	// Body is the request's body.
	//
	// For client requests, a nil body means the request has no
	// body, such as a GET request. The HTTP Client's Transport
	// is responsible for calling the Close method.
	//
	// Body must allow Read to be called concurrently with Close.
	// In particular, calling Close should unblock a Read waiting
	// for input.
	Body io.Reader

	// Signal docs https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
	Signal context.Context
}

Opts are the options for Fetch.

func (*Opts) Clone

func (o *Opts) Clone() *Opts

Clone clones the opts, excluding the Body field.

type Response

type Response struct {
	// OK indicates if the response status code indicates success or not.
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
	OK bool

	// Header maps header keys to values. If the response had multiple
	// headers with the same key, they may be concatenated, with comma
	// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) When
	// Header values are duplicated by other fields in this struct (e.g.,
	// ContentLength, TransferEncoding, Trailer), the field values are
	// authoritative.
	//
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
	Header Header

	// Redirected indicates the request was redirected one or more times.
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/redirected
	Redirected bool

	// StatusCode is the HTTP status code.
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/status
	StatusCode int

	// Status is the HTTP status text e.g. 200 OK.
	//
	// For compatibility this is {StatusCode} {statusText}
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText
	Status string

	// Type has the type of the response.
	//
	// basic: Normal, same origin response, with all headers exposed except "Set-Cookie".
	// cors: Response was received from a valid cross-origin request. Certain headers and the body may be accessed.
	// error: Network error. No useful information describing the error is available. The Response's status is 0, headers are empty and immutable. This is the type for a Response obtained from Response.error().
	// opaque: Response for "no-cors" request to cross-origin resource. Severely restricted.
	// opaqueredirect: The fetch request was made with redirect: "manual". The Response's status is 0, headers are empty, body is null and trailer is empty.
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/type
	Type string

	// The url read-only property of the Response interface contains the URL of
	// the response. The value of the url property will be the final URL
	// obtained after any redirects.
	//
	// https://developer.mozilla.org/en-US/docs/Web/API/Response/url
	URL string

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

Response is the response that returns from the fetch promise.

func Fetch

func Fetch(url string, opts *Opts) (*Response, error)

Fetch uses the JS Fetch API to make requests.

Jump to

Keyboard shortcuts

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