Response

Struct Response 

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

An HTTP response following the WHATWG Fetch specification.

Response represents an HTTP response with all its associated metadata including status code, headers, body, and response type information.

§Body Consumption

Response 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.

§Status Code Validation

The ok() method returns true for status codes in the range 200-299 (inclusive). This follows the HTTP specification for successful responses.

§Examples

use fetchttp::{Response, ReadableStream};

let response = Response::new(
    Some(ReadableStream::from_text("Hello, World!")),
    None
).unwrap();

assert_eq!(response.status(), 200);
assert!(response.ok());

let text = response.text().await.unwrap();
assert_eq!(text, "Hello, World!");

Implementations§

Source§

impl Response

Source

pub fn new( body: Option<ReadableStream>, init: Option<ResponseInit>, ) -> Result<Self>

Create a new HTTP response.

This constructor validates the status code and status text according to HTTP standards and the WHATWG Fetch specification.

§Arguments
  • body - Optional response body
  • init - Optional response configuration
§Returns

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

§Errors
  • TypeError - If the status code is invalid (not 200-599) or status text contains invalid characters
§Examples
use fetchttp::{Response, ResponseInit, ReadableStream};

// Simple 200 OK response
let response = Response::new(
    Some(ReadableStream::from_text("Success")),
    None
).unwrap();
assert_eq!(response.status(), 200);

// Custom 404 response
let mut init = ResponseInit::new();
init.status = Some(404);
init.status_text = Some("Not Found".to_string());

let response = Response::new(None, Some(init)).unwrap();
assert_eq!(response.status(), 404);
assert!(!response.ok());

// Invalid status code will fail
let mut invalid_init = ResponseInit::new();
invalid_init.status = Some(999); // Invalid status code
assert!(Response::new(None, Some(invalid_init)).is_err());
Source

pub fn error() -> Self

Create an error response.

Error responses have a status of 0 and represent network errors or other failures that prevent a proper HTTP response.

§Returns

A new error response.

§Examples
use fetchttp::{Response, ResponseType};

let response = Response::error();
assert_eq!(response.status(), 0);
assert!(!response.ok());
assert_eq!(response.response_type(), ResponseType::Error);
Source

pub fn redirect(url: &str, status: Option<u16>) -> Result<Self>

Create a redirect response.

Redirect responses have a status code in the 3xx range and include a Location header pointing to the redirect target.

§Arguments
  • url - The URL to redirect to
  • status - Optional redirect status code (defaults to 302)
§Returns

A new redirect response, or an error if the status code is invalid.

§Errors
  • TypeError - If the status code is not a valid redirect code
§Examples
use fetchttp::Response;

// Temporary redirect (302)
let response = Response::redirect("https://example.com/new", None).unwrap();
assert_eq!(response.status(), 302);
assert_eq!(
    response.headers().get("location").unwrap().unwrap(),
    "https://example.com/new"
);

// Permanent redirect (301)
let response = Response::redirect("https://example.com/new", Some(301)).unwrap();
assert_eq!(response.status(), 301);

// Invalid redirect status will fail
assert!(Response::redirect("https://example.com", Some(200)).is_err());
Source

pub fn response_type(&self) -> ResponseType

Get the response type.

§Examples
use fetchttp::{Response, ResponseType};

let response = Response::new(None, None).unwrap();
assert_eq!(response.response_type(), ResponseType::Basic);

let error_response = Response::error();
assert_eq!(error_response.response_type(), ResponseType::Error);
Source

pub fn url(&self) -> &str

Get the response URL.

This may be different from the original request URL if redirects occurred.

§Examples
use fetchttp::Response;

let response = Response::new(None, None).unwrap();
assert_eq!(response.url(), "");
Source

pub fn redirected(&self) -> bool

Check if the response is the result of a redirect.

§Examples
use fetchttp::Response;

let response = Response::new(None, None).unwrap();
assert!(!response.redirected());
Source

pub fn status(&self) -> u16

Get the HTTP status code.

§Examples
use fetchttp::{Response, ResponseInit};

let response = Response::new(None, None).unwrap();
assert_eq!(response.status(), 200);

let mut init = ResponseInit::new();
init.status = Some(404);
let response = Response::new(None, Some(init)).unwrap();
assert_eq!(response.status(), 404);
Source

pub fn ok(&self) -> bool

Check if the response represents a successful HTTP status.

Returns true for status codes in the range 200-299 (inclusive).

§Examples
use fetchttp::{Response, ResponseInit};

// 2xx status codes are ok
let response = Response::new(None, None).unwrap(); // 200
assert!(response.ok());

let mut init = ResponseInit::new();
init.status = Some(201);
let response = Response::new(None, Some(init)).unwrap();
assert!(response.ok());

// Other status codes are not ok
let mut init = ResponseInit::new();
init.status = Some(404);
let response = Response::new(None, Some(init)).unwrap();
assert!(!response.ok());

let error_response = Response::error(); // Status 0
assert!(!error_response.ok());
Source

pub fn status_text(&self) -> &str

Get the HTTP status text.

§Examples
use fetchttp::{Response, ResponseInit};

let response = Response::new(None, None).unwrap();
assert_eq!(response.status_text(), "OK");

let mut init = ResponseInit::new();
init.status = Some(404);
let response = Response::new(None, Some(init)).unwrap();
assert_eq!(response.status_text(), "Not Found");
Source

pub fn headers(&self) -> &Headers

Get the response headers.

§Examples
use fetchttp::{Response, ResponseInit, Headers};

let mut headers = Headers::new();
headers.set("Content-Type", "application/json").unwrap();

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

let response = Response::new(None, Some(init)).unwrap();
assert!(response.headers().has("content-type").unwrap());
Source

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

Get the response body.

§Examples
use fetchttp::{Response, ReadableStream};

// Response without body
let response = Response::new(None, None).unwrap();
assert!(response.body().is_none());

// Response with body
let response = Response::new(
    Some(ReadableStream::from_text("content")),
    None
).unwrap();
assert!(response.body().is_some());
Source

pub fn body_used(&self) -> bool

Check if the response body has been used.

§Examples
use fetchttp::{Response, ReadableStream};

let response = Response::new(
    Some(ReadableStream::from_text("content")),
    None
).unwrap();
assert!(!response.body_used());

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

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

Clone the response (WHATWG Fetch API method).

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

§Returns

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

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

let response = Response::new(None, None).unwrap();
let cloned = response.clone_response().unwrap();

assert_eq!(response.status(), cloned.status());
assert_eq!(response.ok(), cloned.ok());
Source

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

Consume the response and return the body as bytes.

§Examples
use fetchttp::{Response, ReadableStream};

let response = Response::new(
    Some(ReadableStream::from_text("Hello, World!")),
    None
).unwrap();

let bytes = response.array_buffer().await.unwrap();
assert_eq!(bytes, b"Hello, World!");
Source

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

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

Source

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

Consume the response and return the body as form data.

Source

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

Consume the response and parse the body as JSON.

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

let data = json!({"message": "Hello", "count": 42});
let response = Response::new(
    Some(ReadableStream::from_json(&data)),
    None
).unwrap();

let parsed: serde_json::Value = response.json().await.unwrap();
assert_eq!(parsed["message"], "Hello");
assert_eq!(parsed["count"], 42);
Source

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

Consume the response and return the body as text.

§Examples
use fetchttp::{Response, ReadableStream};

let response = Response::new(
    Some(ReadableStream::from_text("Hello, World!")),
    None
).unwrap();

let text = response.text().await.unwrap();
assert_eq!(text, "Hello, World!");

Trait Implementations§

Source§

impl Clone for Response

Source§

fn clone(&self) -> Self

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 Response

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