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
impl Response
Sourcepub fn new(
body: Option<ReadableStream>,
init: Option<ResponseInit>,
) -> Result<Self>
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 bodyinit- 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());Sourcepub fn error() -> Self
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);Sourcepub fn redirect(url: &str, status: Option<u16>) -> Result<Self>
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 tostatus- 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());Sourcepub fn response_type(&self) -> ResponseType
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);Sourcepub fn url(&self) -> &str
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(), "");Sourcepub fn redirected(&self) -> bool
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());Sourcepub fn status(&self) -> u16
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);Sourcepub fn ok(&self) -> bool
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());Sourcepub fn status_text(&self) -> &str
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");Sourcepub fn headers(&self) -> &Headers
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());Sourcepub fn body(&self) -> Option<&ReadableStream>
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());Sourcepub fn body_used(&self) -> bool
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)Sourcepub fn clone_response(&self) -> Result<Self>
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());Sourcepub async fn array_buffer(self) -> Result<Bytes>
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!");Sourcepub async fn blob(self) -> Result<Bytes>
pub async fn blob(self) -> Result<Bytes>
Consume the response and return the body as a blob (bytes).
Sourcepub async fn form_data(self) -> Result<String>
pub async fn form_data(self) -> Result<String>
Consume the response and return the body as form data.
Sourcepub async fn json<T: DeserializeOwned>(self) -> Result<T>
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);Sourcepub async fn text(self) -> Result<String>
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!");