HttpResponse

Struct HttpResponse 

Source
pub struct HttpResponse {
    pub status: u16,
    pub headers: LazyHeaders,
    pub body: Vec<u8>,
    /* private fields */
}
Expand description

HTTP response wrapper

The body is stored as Vec<u8> for backwards compatibility. For zero-copy body handling, use with_bytes_body() or body_bytes().

§Performance Note

Response creation is optimized for minimal allocation:

  • headers uses LazyHeaders which doesn’t allocate until first insert
  • body uses Option<Vec<u8>> which doesn’t allocate for empty responses
  • Use FastResponse from armature_core::fast_response for even faster creation

Fields§

§status: u16§headers: LazyHeaders

Response headers with lazy allocation.

§body: Vec<u8>

Response body as raw bytes (legacy field for compatibility).

Implementations§

Source§

impl HttpResponse

Source

pub fn new(status: u16) -> Self

Create a new response with the given status code.

This is optimized for minimal allocation - headers use LazyHeaders which doesn’t allocate until first insert, and body uses Vec::new() which is zero-cost.

Source

pub fn with_capacity(status: u16, capacity: usize) -> Self

Create a new response with pre-allocated body buffer.

This is more efficient than new() when you know you’ll be writing to the body, as it avoids reallocation.

§Example
// Pre-allocate for typical JSON responses
let response = HttpResponse::with_capacity(200, 512);
Source

pub fn ok() -> Self

Create a 200 OK response.

Source

pub fn ok_preallocated() -> Self

Create a 200 OK response with pre-allocated buffer (512 bytes default).

Source

pub fn created() -> Self

Create a 201 Created response.

Source

pub fn no_content() -> Self

Create a 204 No Content response.

Source

pub fn bad_request() -> Self

Create a 400 Bad Request response.

Source

pub fn not_found() -> Self

Create a 404 Not Found response.

Source

pub fn internal_server_error() -> Self

Create a 500 Internal Server Error response.

Source

pub fn with_body(self, body: Vec<u8>) -> Self

Source

pub fn with_bytes_body(self, bytes: Bytes) -> Self

Set the body using Bytes (zero-copy).

This is the most efficient way to set response body data, as it can be passed directly to Hyper without copying.

Source

pub fn with_static_body(self, body: &'static [u8]) -> Self

Set the body from a static byte slice (zero-copy).

Source

pub fn body_bytes(&self) -> Bytes

Get the body as Bytes (zero-copy if stored as Bytes).

This is the key method for zero-copy Hyper body passthrough. If body was set via with_bytes_body(), returns the Bytes directly (O(1)). Otherwise, converts from Vec.

Source

pub fn into_body_bytes(self) -> Bytes

Consume the response and return body as Bytes (zero-copy).

This is the most efficient way to get the body for Hyper, as it avoids cloning when body_bytes is set.

Source

pub fn body_ref(&self) -> &[u8]

Get a reference to the body bytes.

Source

pub fn body_len(&self) -> usize

Get the body length.

Source

pub fn has_bytes_body(&self) -> bool

Check if using zero-copy Bytes storage.

Source

pub fn with_json<T: Serialize>(self, value: &T) -> Result<Self, Error>

Serialize a value as JSON and set it as the response body.

With the simd-json feature enabled, this uses SIMD-accelerated serialization which can be 1.5-2x faster on modern x86_64 CPUs.

The body is stored as Bytes for zero-copy passthrough to Hyper.

§Example
HttpResponse::ok().with_json(&user)?
Source

pub fn with_header(self, key: String, value: String) -> Self

Source

pub fn with_headers(self, headers: HashMap<String, String>) -> Self

Set multiple headers from a HashMap.

Source

pub fn with_status_and_headers( status: u16, headers: HashMap<String, String>, ) -> Self

Create a response with status and headers (for CORS preflight, etc.).

Source

pub fn from_parts( status: u16, headers: HashMap<String, String>, body: Vec<u8>, ) -> Self

Create a response with all components (for compatibility).

This is useful when you need to construct a response with all parts at once.

Source

pub fn accepted() -> Self

Create an accepted response (202).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::accepted();
assert_eq!(response.status, 202);
Source

pub fn unauthorized() -> Self

Create an unauthorized response (401).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::unauthorized();
assert_eq!(response.status, 401);
Source

pub fn forbidden() -> Self

Create a forbidden response (403).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::forbidden();
assert_eq!(response.status, 403);
Source

pub fn conflict() -> Self

Create a conflict response (409).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::conflict();
assert_eq!(response.status, 409);
Source

pub fn service_unavailable() -> Self

Create a service unavailable response (503).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::service_unavailable();
assert_eq!(response.status, 503);
Source

pub fn json<T: Serialize>(value: &T) -> Result<Self, Error>

Shorthand for creating a JSON response with 200 OK status.

§Example
use armature_core::HttpResponse;
use serde_json::json;

let response = HttpResponse::json(&json!({"message": "Hello"})).unwrap();
assert_eq!(response.status, 200);
Source

pub fn html(content: impl Into<String>) -> Self

Create an HTML response with 200 OK status.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::html("<h1>Hello</h1>");
assert_eq!(response.status, 200);
assert_eq!(response.headers.get("Content-Type"), Some(&"text/html; charset=utf-8".to_string()));
Source

pub fn text(content: impl Into<String>) -> Self

Create a plain text response with 200 OK status.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::text("Hello, World!");
assert_eq!(response.status, 200);
assert_eq!(response.headers.get("Content-Type"), Some(&"text/plain; charset=utf-8".to_string()));
Source

pub fn redirect(url: impl Into<String>) -> Self

Create a redirect response (302 Found).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::redirect("https://example.com");
assert_eq!(response.status, 302);
assert_eq!(response.headers.get("Location"), Some(&"https://example.com".to_string()));
Source

pub fn redirect_permanent(url: impl Into<String>) -> Self

Create a permanent redirect response (301 Moved Permanently).

§Example
use armature_core::HttpResponse;
let response = HttpResponse::redirect_permanent("https://example.com");
assert_eq!(response.status, 301);
Source

pub fn see_other(url: impl Into<String>) -> Self

Create a see other redirect response (303 See Other). Useful after a POST request to redirect to a GET.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::see_other("/success");
assert_eq!(response.status, 303);
Source

pub fn empty() -> Self

Alias for no_content() - returns 204 with empty body.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::empty();
assert_eq!(response.status, 204);
Source

pub fn content_type(self, content_type: impl Into<String>) -> Self

Set the Content-Type header.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::ok().content_type("application/xml");
assert_eq!(response.headers.get("Content-Type"), Some(&"application/xml".to_string()));
Source

pub fn cache_control(self, directive: impl Into<String>) -> Self

Set the Cache-Control header.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::ok().cache_control("max-age=3600");
Source

pub fn no_cache(self) -> Self

Mark the response as not cacheable.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::ok().no_cache();
Source

pub fn cookie(self, name: impl Into<String>, value: impl Into<String>) -> Self

Set a cookie on the response.

§Example
use armature_core::HttpResponse;
let response = HttpResponse::ok().cookie("session", "abc123; HttpOnly; Secure");
Source

pub fn body_string(&self) -> String

Get the response body as a string (lossy UTF-8 conversion).

Source

pub fn is_success(&self) -> bool

Check if the response is successful (2xx status code).

Source

pub fn is_redirect(&self) -> bool

Check if the response is a redirect (3xx status code).

Source

pub fn is_client_error(&self) -> bool

Check if the response is a client error (4xx status code).

Source

pub fn is_server_error(&self) -> bool

Check if the response is a server error (5xx status code).

Source§

impl HttpResponse

Source

pub fn into_chunks(self) -> ResponseChunks

Convert to vectored response chunks.

Use this for efficient vectored writes when you have direct socket access.

Source

pub fn to_vectored(&self) -> ResponseChunks

Get IoSlices for vectored write.

This is a convenience method that creates ResponseChunks and returns the slices. For repeated use, prefer into_chunks().

Trait Implementations§

Source§

impl Debug for HttpResponse

Source§

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

Formats the value using the given formatter. Read more
Source§

impl From<HttpResponse> for ResponseChunks

Source§

fn from(response: HttpResponse) -> Self

Converts to this type from the input type.
Source§

impl HttpResponseFromHttp for HttpResponse

Source§

fn from_http_response(resp: Response<Bytes>) -> Self

Create from http crate Response.
Source§

impl IntoHttpResponse for HttpResponse

Source§

fn into_http_response(self) -> Response<Full<Bytes>>

Convert to http crate Response.

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Injectable for T
where T: Send + Sync + 'static,

Source§

fn type_id_of() -> TypeId
where Self: Sized,

Returns the TypeId of this type (for internal use)
Source§

fn type_name_of() -> &'static str
where Self: Sized,

Returns the type name for debugging
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> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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
Source§

impl<T> Provider for T
where T: Injectable,