gossamer/fetch_extra
Extensions to gleam/fetch.
gleam/fetch covers the common case (build a Request, send, read
the body). fetch_extra adds:
- Response accessors that
gleam/http/response.Responsedoesn’t carry: final URL after redirects, redirected flag, body-used flag, response type. is_response_ok, a status-only check that works on anyResponse(body)including after a body consumer has swapped the body type.- A
FetchOptionsbuilder for configuration thatgleam/http/request.Requestdoesn’t carry (cache mode, credentials policy, CORS mode, priority, redirect handling, integrity check, keepalive, abort signal, referrer, referrer policy), withsendvariants that consume it.
When you don’t need extra configuration, prefer gleam/fetch.send
directly.
Examples
import gossamer/fetch_extra
let opts =
fetch_extra.options()
|> fetch_extra.set_cache(fetch_extra.CacheNoCache)
|> fetch_extra.set_keepalive(True)
fetch_extra.send(request, with: opts)
Types
The cache mode for a Request, controlling how it interacts with the
HTTP cache.
pub type Cache {
CacheDefault
CacheForceCache
CacheNoCache
CacheNoStore
CacheOnlyIfCached
CacheReload
}
Constructors
-
CacheDefaultDefault behavior — the cache is consulted and revalidated per normal HTTP caching semantics.
-
CacheForceCacheUse a cached response unconditionally if one exists, ignoring freshness. Fetch from the network only on a cache miss.
-
CacheNoCacheValidate cached responses with the server before using them.
-
CacheNoStoreBypass the cache entirely — neither read from nor write to it.
-
CacheOnlyIfCachedReturn a cached response or fail with a network error. Never hit the network.
-
CacheReloadAlways fetch from the network, but update the cache with the response.
Whether a Request includes credentials (cookies, HTTP auth) for
cross-origin requests.
pub type Credentials {
CredentialsInclude
CredentialsOmit
CredentialsSameOrigin
}
Constructors
-
CredentialsIncludeAlways include credentials, even on cross-origin requests.
-
CredentialsOmitNever send credentials, even on same-origin requests.
-
CredentialsSameOriginSend credentials only on same-origin requests.
Configuration for send and its variants. Unset fields use the
runtime’s default behavior.
pub type FetchOptions {
FetchOptions(
cache: option.Option(Cache),
credentials: option.Option(Credentials),
integrity: String,
keepalive: Bool,
mode: option.Option(Mode),
priority: option.Option(Priority),
redirect: option.Option(Redirect),
referrer: option.Option(String),
referrer_policy: option.Option(ReferrerPolicy),
signal: option.Option(abort_signal.AbortSignal),
)
}
Constructors
-
FetchOptions( cache: option.Option(Cache), credentials: option.Option(Credentials), integrity: String, keepalive: Bool, mode: option.Option(Mode), priority: option.Option(Priority), redirect: option.Option(Redirect), referrer: option.Option(String), referrer_policy: option.Option(ReferrerPolicy), signal: option.Option(abort_signal.AbortSignal), )
The CORS mode for a Request, controlling how cross-origin requests
are handled.
pub type Mode {
ModeCors
ModeNavigate
ModeNoCors
ModeSameOrigin
}
Constructors
-
ModeCorsAllow cross-origin requests subject to CORS preflight checks.
-
ModeNavigateReserved for navigation requests (top-level document loads).
-
ModeNoCorsAllow cross-origin requests with no CORS preflight; the response body is opaque.
-
ModeSameOriginAllow only same-origin requests; cross-origin requests fail.
The priority hint for a Request, indicating relative importance
compared to other requests.
pub type Priority {
PriorityHigh
PriorityLow
PriorityAuto
}
Constructors
-
PriorityHighHigher priority than other requests of the same destination.
-
PriorityLowLower priority than other requests of the same destination.
-
PriorityAutoLet the runtime pick a priority based on the request type and context.
How a Request handles redirect responses.
pub type Redirect {
RedirectError
RedirectFollow
RedirectManual
}
Constructors
-
RedirectErrorReject the response with a network error if the server responds with a redirect.
-
RedirectFollowAutomatically follow redirects (the default).
-
RedirectManualReturn the redirect response opaquely without following it; the caller decides what to do.
The referrer policy for a Request, controlling what URL is sent in
the Referer header.
pub type ReferrerPolicy {
ReferrerNoReferrer
ReferrerNoReferrerWhenDowngrade
ReferrerOrigin
ReferrerOriginWhenCrossOrigin
ReferrerSameOrigin
ReferrerStrictOrigin
ReferrerStrictOriginWhenCrossOrigin
ReferrerUnsafeUrl
}
Constructors
-
ReferrerNoReferrerSend no
Refererheader. -
ReferrerNoReferrerWhenDowngradeSend the full URL, but omit it on a secure-to-insecure downgrade.
-
ReferrerOriginSend only the origin (scheme + host + port).
-
ReferrerOriginWhenCrossOriginSend the full URL on same-origin; only the origin on cross-origin.
-
ReferrerSameOriginSend the full URL on same-origin; nothing on cross-origin.
-
ReferrerStrictOriginSend only the origin, and omit on a secure-to-insecure downgrade.
-
ReferrerStrictOriginWhenCrossOriginSend the full URL on same-origin; the origin on cross-origin; nothing on a secure-to-insecure downgrade.
-
ReferrerUnsafeUrlAlways send the full URL. Discouraged because it can leak sensitive paths.
The classification of a Response. Reflects how the response was
obtained and what content the consumer can access (a ResponseBasic
response exposes its body; a ResponseOpaque response does not).
pub type ResponseType {
ResponseBasic
ResponseCors
ResponseDefault
ResponseError
ResponseOpaque
ResponseOpaqueRedirect
}
Constructors
-
ResponseBasicA same-origin response. The body and most headers are exposed.
-
ResponseCorsA cross-origin response with CORS headers. The body and CORS-safelisted headers are exposed.
-
ResponseDefaultA response from a synthetic source (e.g.,
Response.new/from_string). -
ResponseErrorA network error response. The body is opaque and consumers can’t read it.
-
ResponseOpaqueA no-cors cross-origin response. The body and most headers are hidden.
-
ResponseOpaqueRedirectA redirect response received when the request was made with redirect mode
RedirectManualand the server replied with a redirect. The body is hidden.
Values
pub fn is_response_body_used(
response: response.Response(fetch.FetchBody),
) -> Bool
True when the body has already been read.
pub fn is_response_ok(response: response.Response(body)) -> Bool
True when the status code is in the 200-299 range. Derived from
status alone, so it works on any Response(body) — including after
a body consumer has swapped the body type.
pub fn is_response_redirected(
response: response.Response(fetch.FetchBody),
) -> Bool
True when the response is the result of one or more redirects.
pub fn options() -> FetchOptions
A FetchOptions with no fields set. Pass directly to send to use
runtime defaults for every field, or chain setters to override
individual fields.
pub fn response_clone(
response: response.Response(fetch.FetchBody),
) -> Result(response.Response(fetch.FetchBody), fetch.FetchError)
Clones a Response. The cloned response has its own independent body
stream, so the original and clone can each be consumed once. Returns
Error(fetch.UnableToReadBody) if the body has already been read or
is locked to a reader.
pub fn response_json(
json_string: String,
) -> response.Response(String)
Builds a Response(String) carrying a JSON body. Sets status 200
and the content-type: application/json header. The caller is
responsible for serializing their data to JSON (see gleam/json).
Examples
fetch_extra.response_json("{\"ok\":true}")
pub fn response_type(
response: response.Response(fetch.FetchBody),
) -> ResponseType
The response type.
On Bun, responses fetched from synthetic sources such as data:
URLs report ResponseDefault where Node and Deno report
ResponseBasic.
pub fn response_url(
response: response.Response(fetch.FetchBody),
) -> String
The final URL after redirects. "" for synthetic responses with no
URL.
pub fn send(
request: request.Request(String),
with options: FetchOptions,
) -> promise.Promise(
Result(response.Response(fetch.FetchBody), fetch.FetchError),
)
Sends a Request(String) with the given options. Returns
Error(fetch.NetworkError(_)) on network failure. When an
AbortSignal on the options aborts the request, the failure
surfaces as NetworkError(_); inspect the signal via
abort_signal.is_aborted and
abort_signal.reason to recover
the abort reason. A non-2xx status is still a successful send.
pub fn send_bits(
request: request.Request(BitArray),
with options: FetchOptions,
) -> promise.Promise(
Result(response.Response(fetch.FetchBody), fetch.FetchError),
)
Sends a Request(BitArray) with the given options. See
send for error semantics.
pub fn send_form_data(
request: request.Request(form_data.FormData),
with options: FetchOptions,
) -> promise.Promise(
Result(response.Response(fetch.FetchBody), fetch.FetchError),
)
Sends a Request(FormData) with the given options. The body is
encoded as multipart/form-data. See send for error
semantics.
pub fn send_stream(
request: request.Request(
readable_stream.ReadableStream(BitArray),
),
with options: FetchOptions,
) -> promise.Promise(
Result(response.Response(fetch.FetchBody), fetch.FetchError),
)
Sends a Request(ReadableStream(BitArray)) with the given options.
The body is streamed as the request is sent (the Fetch spec requires
duplex: "half", which gossamer sets automatically). Returns
Error(fetch.UnableToReadBody) if the body stream is already locked
to a reader. See send for the remaining error semantics.
pub fn set_cache(
opts: FetchOptions,
cache: Cache,
) -> FetchOptions
Sets the cache mode, controlling how the request interacts with the HTTP cache.
pub fn set_credentials(
opts: FetchOptions,
credentials: Credentials,
) -> FetchOptions
Sets the credentials policy, controlling whether cookies and HTTP auth are sent with cross-origin requests.
pub fn set_integrity(
opts: FetchOptions,
integrity: String,
) -> FetchOptions
Sets a subresource integrity hash that the response must match; the fetch fails if the body doesn’t hash to the given value.
pub fn set_keepalive(
opts: FetchOptions,
keepalive: Bool,
) -> FetchOptions
Sets the keepalive flag, allowing the request to outlive its originating context (subject to per-origin size limits).
pub fn set_mode(opts: FetchOptions, mode: Mode) -> FetchOptions
Sets the CORS mode, controlling how cross-origin requests are handled.
pub fn set_priority(
opts: FetchOptions,
priority: Priority,
) -> FetchOptions
Sets the priority hint, indicating relative importance compared to other requests.
pub fn set_redirect(
opts: FetchOptions,
redirect: Redirect,
) -> FetchOptions
Sets how the request handles redirects.
pub fn set_referrer(
opts: FetchOptions,
referrer: String,
) -> FetchOptions
Sets the referrer URL. Use "about:client" for the default behavior
or "" to omit the Referer header entirely.
pub fn set_referrer_policy(
opts: FetchOptions,
referrer_policy: ReferrerPolicy,
) -> FetchOptions
Sets the referrer policy, controlling what URL is sent in the
Referer header.
pub fn set_signal(
opts: FetchOptions,
signal: abort_signal.AbortSignal,
) -> FetchOptions
Sets the abort signal, allowing the request to be cancelled imperatively or after a timeout.