Struct Request

Source
pub struct Request { /* private fields */ }
Expand description

An HTTP request following the WHATWG Fetch specification.

Request represents an HTTP request with all its associated metadata including URL, method, headers, body, and fetch options. Requests are immutable once created, but can be cloned if the body hasn’t been consumed.

§Body Consumption

Request bodies can only be consumed once. After calling any body consumption method (text(), json(), array_buffer(), etc.), the body is marked as used and cannot be consumed again.

§Examples

use fetchttp::{Request, RequestInit};

// Simple GET request
let request = Request::new("https://api.example.com/data", None).unwrap();
println!("Method: {}", request.method());
println!("URL: {}", request.url());

// POST request with configuration
let mut init = RequestInit::new();
init.method = Some("POST".to_string());

let request = Request::new("https://api.example.com/submit", Some(init)).unwrap();
assert_eq!(request.method(), "POST");

Implementations§

Source§

impl Request

Source

pub fn new(input: &str, init: Option<RequestInit>) -> Result<Self>

Create a new HTTP request.

This constructor validates the URL and request configuration, applies defaults for unspecified options, and performs validation according to the WHATWG Fetch specification.

§Arguments
  • input - The URL to request (must be a valid absolute URL)
  • init - Optional request configuration
§Returns

A new Request instance, or an error if validation fails.

§Errors
  • TypeError - If the URL is invalid, method is invalid, or GET/HEAD requests have a body
§Examples
use fetchttp::{Request, RequestInit, ReadableStream};

// Simple GET request
let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.method(), "GET");

// POST request with body
let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_text("data"));

let request = Request::new("https://example.com/api", Some(init)).unwrap();
assert_eq!(request.method(), "POST");

// Invalid URL will fail
assert!(Request::new("not-a-url", None).is_err());

// GET with body will fail
let mut invalid_init = RequestInit::new();
invalid_init.method = Some("GET".to_string());
invalid_init.body = Some(ReadableStream::from_text("body"));
assert!(Request::new("https://example.com", Some(invalid_init)).is_err());
Source

pub fn url(&self) -> &str

Get the request URL.

§Returns

The request URL as a string.

§Examples
use fetchttp::Request;

let request = Request::new("https://api.example.com/users?page=1", None).unwrap();
assert_eq!(request.url(), "https://api.example.com/users?page=1");
Source

pub fn method(&self) -> &str

Get the request method.

§Returns

The HTTP method as a string (uppercase for standard methods).

§Examples
use fetchttp::{Request, RequestInit};

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.method(), "GET");

let mut init = RequestInit::new();
init.method = Some("post".to_string()); // Will be normalized to uppercase
let request = Request::new("https://example.com", Some(init)).unwrap();
assert_eq!(request.method(), "POST");
Source

pub fn headers(&self) -> &Headers

Get the request headers.

§Returns

A reference to the request headers.

§Examples
use fetchttp::{Request, RequestInit, Headers};

let mut headers = Headers::new();
headers.set("User-Agent", "MyApp/1.0").unwrap();

let mut init = RequestInit::new();
init.headers = Some(headers);

let request = Request::new("https://example.com", Some(init)).unwrap();
assert!(request.headers().has("user-agent").unwrap());
Source

pub fn body(&self) -> Option<&ReadableStream>

Get the request body.

§Returns

An optional reference to the request body.

§Examples
use fetchttp::{Request, RequestInit, ReadableStream};

// Request without body
let request = Request::new("https://example.com", None).unwrap();
assert!(request.body().is_none());

// Request with body
let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_text("data"));

let request = Request::new("https://example.com", Some(init)).unwrap();
assert!(request.body().is_some());
Source

pub fn body_used(&self) -> bool

Check if the request body has been used.

§Returns

true if the body has been consumed, false otherwise.

§Examples
use fetchttp::{Request, RequestInit, ReadableStream};

let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_text("data"));

let request = Request::new("https://example.com", Some(init)).unwrap();
assert!(!request.body_used());

// After consuming the body, it would be marked as used
// (body consumption moves the request, so we can't show this in the example)
Source

pub fn mode(&self) -> RequestMode

Get the request mode.

§Examples
use fetchttp::{Request, RequestMode};

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.mode(), RequestMode::Cors);
Source

pub fn credentials(&self) -> RequestCredentials

Get the credentials mode.

§Examples
use fetchttp::{Request, RequestCredentials};

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.credentials(), RequestCredentials::SameOrigin);
Source

pub fn cache(&self) -> RequestCache

Get the cache mode.

§Examples
use fetchttp::{Request, RequestCache};

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.cache(), RequestCache::Default);
Source

pub fn redirect(&self) -> RequestRedirect

Get the redirect mode.

§Examples
use fetchttp::{Request, RequestRedirect};

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.redirect(), RequestRedirect::Follow);
Source

pub fn referrer(&self) -> &str

Get the referrer information.

§Examples
use fetchttp::Request;

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.referrer(), "about:client");
Source

pub fn referrer_policy(&self) -> &str

Get the referrer policy.

Source

pub fn integrity(&self) -> &str

Get the integrity metadata.

§Examples
use fetchttp::Request;

let request = Request::new("https://example.com", None).unwrap();
assert_eq!(request.integrity(), "");
Source

pub fn keepalive(&self) -> bool

Get the keepalive flag.

§Examples
use fetchttp::Request;

let request = Request::new("https://example.com", None).unwrap();
assert!(!request.keepalive());
Source

pub fn signal(&self) -> Option<&AbortSignal>

Get the abort signal.

§Returns

An optional reference to the abort signal.

§Examples
use fetchttp::{Request, RequestInit, AbortController};

let controller = AbortController::new();
let mut init = RequestInit::new();
init.signal = Some(controller.signal().clone());

let request = Request::new("https://example.com", Some(init)).unwrap();
assert!(request.signal().is_some());
Source

pub fn clone_request(&self) -> Result<Self>

Clone the request (WHATWG Fetch API method).

This method follows the WHATWG Fetch specification for cloning requests. It will fail if the request body has already been used.

§Returns

A cloned request, or an error if the body has been used.

§Errors
  • TypeError - If the request body has already been consumed
§Examples
use fetchttp::Request;

let request = Request::new("https://example.com", None).unwrap();
let cloned = request.clone_request().unwrap();

assert_eq!(request.url(), cloned.url());
assert_eq!(request.method(), cloned.method());
Source

pub async fn array_buffer(self) -> Result<Bytes>

Consume the request and return the body as bytes.

§Examples
use fetchttp::{Request, RequestInit, ReadableStream};

let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_text("Hello, World!"));

let request = Request::new("https://example.com", Some(init)).unwrap();
let bytes = request.array_buffer().await.unwrap();
assert_eq!(bytes, b"Hello, World!");
Source

pub async fn blob(self) -> Result<Bytes>

Consume the request and return the body as a blob (bytes).

Source

pub async fn form_data(self) -> Result<String>

Consume the request and return the body as form data.

Source

pub async fn json<T: DeserializeOwned>(self) -> Result<T>

Consume the request and parse the body as JSON.

§Examples
use fetchttp::{Request, RequestInit, ReadableStream};
use serde_json::json;

let data = json!({"name": "John", "age": 30});

let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_json(&data));

let request = Request::new("https://example.com", Some(init)).unwrap();
let parsed: serde_json::Value = request.json().await.unwrap();
assert_eq!(parsed["name"], "John");
Source

pub async fn text(self) -> Result<String>

Consume the request and return the body as text.

§Examples
use fetchttp::{Request, RequestInit, ReadableStream};

let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_text("Hello, World!"));

let request = Request::new("https://example.com", Some(init)).unwrap();
let text = request.text().await.unwrap();
assert_eq!(text, "Hello, World!");

Trait Implementations§

Source§

impl Clone for Request

Source§

fn clone(&self) -> Request

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Request

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more