Response

Struct Response 

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

An HTTP response with status, headers, and body.

Response represents a complete HTTP response that can be constructed, modified, and sent back to clients. It provides comprehensive methods for working with all aspects of HTTP responses including:

  • Status codes - Setting and querying HTTP status codes (200, 404, 500, etc.)
  • Headers - Managing HTTP headers for metadata, caching, content type, etc.
  • Body content - Handling response payloads in various formats
  • HTTP version - Specifying the HTTP protocol version
  • Extensions - Storing custom application data

The response type integrates with the body system to provide convenient methods for handling different content types like JSON, form data, files, and raw bytes.

§Examples

§Creating Basic Responses

use http_kit::{Response, StatusCode};

// Success response with text
let ok = Response::new(200, "Operation successful");

// Error response
let error = Response::new(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong");

// Empty response
let empty = Response::empty();

§Building Rich Responses

use http_kit::Response;

let response = Response::new(201, "Created")
    .header(http::header::LOCATION, "/api/users/123")
    .header(http::header::CONTENT_TYPE, "text/plain");

§Working with Body Content

use http_kit::Response;

let mut response = Response::new(200, "Hello, world!");

// Read the body content
let content = response.into_string().await?;
assert_eq!(content, "Hello, world!");

Implementations§

Source§

impl Response

Source

pub fn new<S>(status: S, body: impl Into<Body>) -> Self
where S: TryInto<StatusCode>, S::Error: Debug,

Creates a new HTTP response with the specified status code and body.

This is the primary constructor for building responses. The body can be any type that converts to Body, including strings, byte vectors, and Bytes objects.

§Arguments
  • status - The HTTP status code (or value convertible to StatusCode)
  • body - The response body (any type convertible to Body)
§Examples
use http_kit::{Response, StatusCode};

// With numeric status code
let response = Response::new(200, "Success");

// With StatusCode enum
let response = Response::new(StatusCode::CREATED, "Resource created");

// With byte vector
let response = Response::new(200, vec![72, 101, 108, 108, 111]);

// With string
let response = Response::new(200, "Hello, world!".to_string());
Source

pub fn empty() -> Self

Creates an empty HTTP response with status 200 OK.

This is a convenience method for creating responses that don’t need body content, such as successful operations that only need to indicate completion.

§Examples
use http_kit::Response;

let response = Response::empty();
assert_eq!(response.status(), http::StatusCode::OK);
Source

pub const fn status(&self) -> StatusCode

Returns the HTTP status code of this response.

§Examples
use http_kit::{Response, StatusCode};

let response = Response::new(404, "Not found");
assert_eq!(response.status(), StatusCode::NOT_FOUND);
Source

pub fn status_mut(&mut self) -> &mut StatusCode

Returns a mutable reference to the HTTP status code.

This allows direct modification of the status code.

§Examples
use http_kit::{Response, StatusCode};

let mut response = Response::empty();
*response.status_mut() = StatusCode::CREATED;
assert_eq!(response.status(), StatusCode::CREATED);
Source

pub fn set_status(&mut self, status: StatusCode)

Sets the HTTP status code for this response.

§Arguments
  • status - The new status code
§Examples
use http_kit::{Response, StatusCode};

let mut response = Response::empty();
response.set_status(StatusCode::NOT_FOUND);
assert_eq!(response.status(), StatusCode::NOT_FOUND);
Source

pub const fn version(&self) -> Version

Returns the HTTP version for this response.

§Examples
use http_kit::{Response, Version};

let response = Response::empty();
// Default version is typically HTTP/1.1
assert_eq!(response.version(), Version::HTTP_11);
Source

pub fn version_mut(&mut self) -> &mut Version

Returns a mutable reference to the HTTP version.

This allows direct modification of the HTTP version.

§Examples
use http_kit::{Response, Version};

let mut response = Response::empty();
*response.version_mut() = Version::HTTP_2;
assert_eq!(response.version(), Version::HTTP_2);
Source

pub fn set_version(&mut self, version: Version)

Sets the HTTP version for this response.

§Arguments
  • version - The HTTP version to use
§Examples
use http_kit::{Response, Version};

let mut response = Response::empty();
response.set_version(Version::HTTP_2);
assert_eq!(response.version(), Version::HTTP_2);
Source

pub const fn headers(&self) -> &HeaderMap

Returns a reference to the HTTP headers.

§Examples
use http_kit::Response;

let response = Response::new(200, "OK")
    .header(http::header::CONTENT_TYPE, "text/plain");

let headers = response.headers();
assert!(headers.contains_key(http::header::CONTENT_TYPE));
Source

pub fn headers_mut(&mut self) -> &mut HeaderMap

Returns a mutable reference to the HTTP headers.

This allows direct manipulation of the header map.

§Examples
use http_kit::Response;

let mut response = Response::empty();
response.headers_mut().insert(
    http::header::CONTENT_TYPE,
    "application/json".parse().unwrap()
);
Source

pub fn get_header(&self, name: HeaderName) -> Option<&HeaderValue>

Returns the first value for the given header name.

If the header has multiple values, only the first one is returned. Returns None if the header is not present.

§Arguments
  • name - The header name to look up
§Examples
use http_kit::Response;

let response = Response::new(200, "OK")
    .header(http::header::CONTENT_TYPE, "application/json");

if let Some(content_type) = response.get_header(http::header::CONTENT_TYPE) {
    assert_eq!(content_type, "application/json");
}
Source

pub fn get_headers(&self, name: HeaderName) -> GetAll<'_, HeaderValue>

Returns an iterator over all values for a given header name.

This method retrieves all values associated with a header name, since HTTP headers can have multiple values. The returned iterator will yield each value in the order they were added.

§Arguments
  • name - The header name to get values for
§Examples
use http_kit::Response;

let response = Response::new(200, "OK")
    .header(http::header::SET_COOKIE, "session=123")
    .header(http::header::SET_COOKIE, "theme=dark");

for cookie in response.get_headers(http::header::SET_COOKIE) {
    // Iterate over each Set-Cookie header value
}
Source

pub fn append_header(&mut self, name: HeaderName, value: HeaderValue)

Appends a header value without removing existing values.

If a header with the same name already exists, the new value is added alongside the existing values rather than replacing them.

§Arguments
  • name - The header name
  • value - The header value to append
§Examples
use http_kit::Response;

let mut response = Response::empty();
response.append_header(http::header::SET_COOKIE, "session=abc123".parse().unwrap());
response.append_header(http::header::SET_COOKIE, "theme=dark".parse().unwrap());
// Both cookies will be present in the response
Source

pub fn insert_header( &mut self, name: HeaderName, value: HeaderValue, ) -> Option<HeaderValue>

Inserts a header value, replacing any existing values.

If a header with the same name already exists, it is completely replaced with the new value.

§Arguments
  • name - The header name
  • value - The header value
§Returns

Returns the previous header value if one existed.

§Examples
use http_kit::Response;

let mut response = Response::empty();
let old_value = response.insert_header(
    http::header::SERVER,
    "http-kit/1.0".parse().unwrap()
);
assert!(old_value.is_none());

let old_value = response.insert_header(
    http::header::SERVER,
    "http-kit/2.0".parse().unwrap()
);
assert!(old_value.is_some());
Source

pub fn header<V>(self, name: HeaderName, value: V) -> Self
where V: TryInto<HeaderValue>, V::Error: Debug,

Sets an HTTP header and returns the modified response.

This is a builder-style method that allows method chaining. If you need to modify an existing response, use insert_header instead.

§Arguments
  • name - The header name
  • value - The header value
§Examples
use http_kit::Response;

let response = Response::new(200, "OK")
    .header(http::header::CONTENT_TYPE, "application/json")
    .header(http::header::SERVER, "http-kit/1.0");
Source

pub const fn extensions(&self) -> &Extensions

Returns a reference to the response extensions.

Extensions provide a type-safe way to store additional data associated with the response that doesn’t fit into standard HTTP fields.

§Examples
use http_kit::Response;

let response = Response::empty();
let extensions = response.extensions();
// Check if a specific type is stored
let timing: Option<&u64> = extensions.get();
Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Returns a mutable reference to the response extensions.

This allows modification of the extensions map.

§Examples
use http_kit::Response;

let mut response = Response::empty();
response.extensions_mut().insert(42u32);
Source

pub fn get_extension<T: Send + Sync + 'static>(&self) -> Option<&T>

Returns a reference to an extension of the specified type.

§Type Parameters
  • T - The type to retrieve from extensions
§Examples
use http_kit::Response;

let mut response = Response::empty();
response.insert_extension(42u32);

if let Some(value) = response.get_extension::<u32>() {
    assert_eq!(*value, 42);
}
Source

pub fn get_mut_extension<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>

Returns a mutable reference to an extension of the specified type.

§Type Parameters
  • T - The type to retrieve from extensions
§Examples
use http_kit::Response;

let mut response = Response::empty();
response.insert_extension(42u32);

if let Some(value) = response.get_mut_extension::<u32>() {
    *value = 100;
}
Source

pub fn remove_extension<T: Send + Sync + 'static>(&mut self) -> Option<T>

Removes and returns an extension of the specified type.

§Type Parameters
  • T - The type to remove from extensions
§Returns

Returns the removed value if it existed, or None if it wasn’t present.

§Examples
use http_kit::Response;

let mut response = Response::empty();
response.insert_extension(42u32);

let removed = response.remove_extension::<u32>();
assert_eq!(removed, Some(42));

let removed_again = response.remove_extension::<u32>();
assert_eq!(removed_again, None);
Source

pub fn insert_extension<T: Send + Sync + Clone + 'static>( &mut self, extension: T, ) -> Option<T>

Inserts an extension value, returning any previous value of the same type.

§Type Parameters
  • T - The type to insert into extensions
§Arguments
  • extension - The value to insert
§Returns

Returns the previous value of the same type if one existed.

§Examples
use http_kit::Response;

let mut response = Response::empty();

let old_value = response.insert_extension(42u32);
assert_eq!(old_value, None);

let old_value = response.insert_extension(100u32);
assert_eq!(old_value, Some(42));
Source

pub fn take_body(&mut self) -> Result<Body, BodyFrozen>

Takes the response body, leaving a frozen (unusable) body in its place.

This method extracts the body from the response while ensuring it cannot be accessed again. This is useful when you need to consume the body for processing while preventing accidental double-consumption.

§Errors

Returns BodyFrozen if the body has already been taken.

§Examples
use http_kit::Response;

let mut response = Response::new(200, "Hello, world!");
let body = response.take_body()?;
// response.take_body() would now return an error
Source

pub fn replace_body(&mut self, body: impl Into<Body>) -> Body

Replaces the response body and returns the previous body.

This method swaps the current body with a new one, returning the original body. This is useful for body transformations or when you need to temporarily substitute the body content.

§Arguments
  • body - The new body to set (anything convertible to Body)
§Examples
use http_kit::Response;

let mut response = Response::new(200, "Original content");
let old_body = response.replace_body("New content");
// old_body contains "Original content"
// response now contains "New content"
Source

pub fn swap_body(&mut self, body: &mut Body) -> Result<(), BodyFrozen>

Swaps the response body with another body.

This method exchanges the contents of the response body with another body, provided that the response body is not frozen.

§Arguments
  • body - The body to swap with
§Errors

Returns BodyFrozen if the response body has been frozen/consumed.

§Examples
use http_kit::{Response, Body};

let mut response = Response::new(200, "Response content");
let mut other_body = Body::from_bytes("Other content");
response.swap_body(&mut other_body)?;

// Now response contains "Other content"
// and other_body contains "Response content"
Source

pub fn map_body<F>(self, f: F) -> Self
where F: FnOnce(Body) -> Body,

Transforms the response body using the provided function.

This method allows you to apply a transformation to the response body in a functional style, returning a new response with the transformed body.

§Arguments
  • f - A function that takes the current body and returns a new body
§Examples
use http_kit::{Response, Body};

let response = Response::new(200, "original")
    .map_body(|body| {
        // Transform body to uppercase JSON
        Body::from_bytes(r#"{"message": "ORIGINAL"}"#)
    });
Source

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

Sets the body from a JSON-serializable value.

This method serializes the provided value to JSON and sets it as the response body. It also automatically sets the Content-Type header to application/json.

§Arguments
  • value - Any value that implements serde::Serialize
§Errors

Returns serde_json::Error if JSON serialization fails.

§Examples
use http_kit::Response;
use serde::Serialize;

#[derive(Serialize)]
struct ApiResponse { success: bool, message: String }

let data = ApiResponse {
    success: true,
    message: "Operation completed".to_string(),
};

let response = Response::empty().json(&data)?;
Source

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

Sets the body from a form-serializable value.

This method serializes the provided value to URL-encoded form data and sets it as the response body. It also automatically sets the Content-Type header to application/x-www-form-urlencoded.

§Arguments
  • value - Any value that implements serde::Serialize
§Errors

Returns serde_urlencoded::ser::Error if form serialization fails.

§Examples
use http_kit::Response;
use serde::Serialize;

#[derive(Serialize)]
struct FormData { key: String, value: String }

let data = FormData {
    key: "name".to_string(),
    value: "Alice".to_string(),
};

let response = Response::empty().form(&data)?;
Source

pub async fn into_bytes(&mut self) -> Result<Bytes, BodyError>

Consumes the response body and returns its data as bytes.

This method takes the response body and reads all its data into memory, returning it as a Bytes object. The body becomes unavailable after this call.

§Errors

Returns BodyError if:

  • The body has already been consumed
  • An I/O error occurs while reading streaming data
§Examples
use http_kit::Response;

let mut response = Response::new(200, "Hello, world!");
let bytes = response.into_bytes().await?;
assert_eq!(bytes, "Hello, world!");
Source

pub async fn into_string(&mut self) -> Result<ByteStr, BodyError>

Consumes the response body and returns its data as a UTF-8 string.

This method takes the response body, reads all its data into memory, and converts it to a UTF-8 string. The body becomes unavailable after this call.

§Errors

Returns BodyError if:

  • The body has already been consumed
  • An I/O error occurs while reading streaming data
  • The body contains invalid UTF-8 sequences
§Examples
use http_kit::Response;

let mut response = Response::new(200, "Hello, world!");
let text = response.into_string().await?;
assert_eq!(text, "Hello, world!");
Source

pub async fn into_json<'a, T>(&'a mut self) -> Result<T, Error>
where T: Deserialize<'a>,

Deserializes the response body as JSON into the specified type.

This method reads the response body and attempts to deserialize it as JSON. It validates that the Content-Type header is application/json before attempting deserialization, making it safe for API clients.

The deserialization is performed with zero-copy when possible by working directly with the buffered byte data.

§Errors

Returns crate::Error if:

  • The Content-Type header is not application/json
  • The body has already been consumed
  • The JSON is malformed or doesn’t match the target type
§Examples
use http_kit::Response;
use serde::Deserialize;

#[derive(Deserialize)]
struct ApiResponse { success: bool, message: String }

let json_data = r#"{"success": true, "message": "OK"}"#;
let mut response = Response::new(200, json_data)
    .header(http::header::CONTENT_TYPE, "application/json");

let data: ApiResponse = response.into_json().await?;
assert!(data.success);
Source

pub async fn into_form<'a, T>(&'a mut self) -> Result<T, Error>
where T: Deserialize<'a>,

Deserializes the response body as URL-encoded form data into the specified type.

This method reads the response body and attempts to deserialize it as application/x-www-form-urlencoded data. It validates that the Content-Type header matches before attempting deserialization.

The deserialization is performed with zero-copy when possible by working directly with the buffered byte data.

§Errors

Returns crate::Error if:

  • The Content-Type header is not application/x-www-form-urlencoded
  • The body has already been consumed
  • The form data is malformed or doesn’t match the target type
§Examples
use http_kit::Response;
use serde::Deserialize;

#[derive(Deserialize)]
struct FormResponse { status: String, code: u32 }

let form_data = "status=success&code=200";
let mut response = Response::new(200, form_data)
    .header(http::header::CONTENT_TYPE, "application/x-www-form-urlencoded");

let data: FormResponse = response.into_form().await?;
assert_eq!(data.status, "success");
Source

pub fn mime(self, mime: Mime) -> Self

Sets the MIME type for the response.

This method sets the Content-Type header using a parsed MIME type, providing type safety and validation for content types.

§Arguments
  • mime - The MIME type to set
§Examples
use http_kit::Response;
use mime;

let response = Response::new(200, "Hello, world!")
    .mime(mime::TEXT_PLAIN);
Source

pub fn get_mime(&self) -> Option<Mime>

Parses the Content-Type header and returns a MIME type.

This method attempts to parse the Content-Type header value as a MIME type, providing structured access to content type information.

§Returns

Returns Some(mime::Mime) if the header exists and can be parsed, or None if the header is missing or invalid.

§Examples
use http_kit::Response;
use mime;

let response = Response::new(200, "Hello")
    .header(http::header::CONTENT_TYPE, "text/plain; charset=utf-8");

if let Some(mime_type) = response.get_mime() {
    assert_eq!(mime_type.type_(), mime::TEXT);
    assert_eq!(mime_type.subtype(), mime::PLAIN);
}

Trait Implementations§

Source§

impl Debug for Response

Source§

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

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

impl From<&[u8]> for Response

Source§

fn from(value: &[u8]) -> Self

Converts to this type from the input type.
Source§

impl From<&str> for Response

Source§

fn from(value: &str) -> Self

Converts to this type from the input type.
Source§

impl From<ByteStr> for Response

Source§

fn from(value: ByteStr) -> Self

Converts to this type from the input type.
Source§

impl From<Bytes> for Response

Source§

fn from(value: Bytes) -> Self

Converts to this type from the input type.
Source§

impl From<Response<Body>> for Response

Source§

fn from(response: Response<Body>) -> Self

Converts to this type from the input type.
Source§

impl From<Response> for Response<Body>

Source§

fn from(response: Response) -> Self

Converts to this type from the input type.
Source§

impl From<String> for Response

Source§

fn from(value: String) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for Response

Source§

fn from(value: Vec<u8>) -> Self

Converts to this type from the input type.

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