Request

Struct Request 

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

An HTTP request with headers, body, and metadata.

Request represents an HTTP request that can be constructed, modified, and processed. It provides methods for working with all aspects of HTTP requests including:

  • HTTP method (GET, POST, PUT, DELETE, etc.)
  • URI/URL for the request target
  • Headers for metadata like content type, authorization, etc.
  • Body for request payload data
  • Extensions for storing custom application data
  • HTTP version information

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

§Examples

§Basic Request Creation

use http_kit::Request;
use http::{Method, Uri};

// Using convenience methods
let get_req = Request::get("/api/users");
let post_req = Request::post("/api/users");

// Using the general constructor
let put_req = Request::new(Method::PUT, "/api/users/123");

§Working with Headers

use http_kit::Request;

let mut request = Request::get("/api/data")
    .header(http::header::ACCEPT, "application/json")
    .header(http::header::USER_AGENT, "MyApp/1.0");

// Access headers
if let Some(accept) = request.get_header(http::header::ACCEPT) {
    println!("Accept header: {:?}", accept);
}

§Request Body Handling

use http_kit::Request;

let mut request = Request::post("/api/echo");
request.replace_body("Hello, server!");

// Take body for processing
let body = request.take_body()?;
let data = body.into_bytes().await?;

Implementations§

Source§

impl Request

Source

pub fn new<U>(method: Method, uri: U) -> Self
where U: TryInto<Uri>, U::Error: Debug,

Creates a new HTTP request with the specified method and URI.

This is the general-purpose constructor for creating requests. For common HTTP methods, consider using the convenience methods like Request::get, Request::post, etc.

§Arguments
  • method - The HTTP method (GET, POST, PUT, DELETE, etc.)
  • uri - The request URI/URL
§Panics

Panics if the URI cannot be parsed into a valid Uri.

§Examples
use http_kit::Request;
use http::Method;

let request = Request::new(Method::PATCH, "/api/users/123");
assert_eq!(request.method(), &Method::PATCH);
Source

pub fn get<U>(uri: U) -> Self
where U: TryInto<Uri>, U::Error: Debug,

Creates a new GET request with the specified URI.

This is a convenience method for creating GET requests, which are commonly used for retrieving data from servers.

§Arguments
  • uri - The request URI/URL
§Examples
use http_kit::Request;

let request = Request::get("/api/users");
assert_eq!(request.method(), &http::Method::GET);
assert_eq!(request.uri().path(), "/api/users");
Source

pub fn post<U>(uri: U) -> Self
where U: TryInto<Uri>, U::Error: Debug,

Creates a new POST request with the specified URI.

This is a convenience method for creating POST requests, which are commonly used for submitting data to servers, creating resources, or triggering actions.

§Arguments
  • uri - The request URI/URL
§Examples
use http_kit::Request;

let request = Request::post("/api/users");
assert_eq!(request.method(), &http::Method::POST);
Source

pub fn put<U>(uri: U) -> Self
where U: TryInto<Uri>, U::Error: Debug,

Creates a new PUT request with the specified URI.

This is a convenience method for creating PUT requests, which are commonly used for updating or replacing resources on the server.

§Arguments
  • uri - The request URI/URL
§Examples
use http_kit::Request;

let request = Request::put("/api/users/123");
assert_eq!(request.method(), &http::Method::PUT);
Source

pub fn delete<U>(uri: U) -> Self
where U: TryInto<Uri>, U::Error: Debug,

Creates a new DELETE request with the specified URI.

This is a convenience method for creating DELETE requests, which are commonly used for removing resources from the server.

§Arguments
  • uri - The request URI/URL
§Examples
use http_kit::Request;

let request = Request::delete("/api/users/123");
assert_eq!(request.method(), &http::Method::DELETE);
Source

pub const fn parts(&self) -> &Parts

Returns a reference to the request parts.

The request parts contain all the HTTP metadata including method, URI, version, headers, and extensions, but not the body.

§Examples
use http_kit::Request;

let request = Request::get("/api/users");
let parts = request.parts();
println!("Method: {}, URI: {}", parts.method, parts.uri);
Source

pub fn parts_mut(&mut self) -> &mut Parts

Returns a mutable reference to the request parts.

This allows modification of the HTTP metadata including method, URI, version, headers, and extensions.

§Examples
use http_kit::Request;
use http::Method;

let mut request = Request::get("/api/users");
request.parts_mut().method = Method::POST;
assert_eq!(request.method(), &Method::POST);
Source

pub const fn method(&self) -> &Method

Returns a reference to the HTTP method.

§Examples
use http_kit::Request;
use http::Method;

let request = Request::post("/api/data");
assert_eq!(request.method(), &Method::POST);
Source

pub fn method_mut(&mut self) -> &mut Method

Returns a mutable reference to the HTTP method.

§Examples
use http_kit::Request;
use http::Method;

let mut request = Request::get("/api/users");
*request.method_mut() = Method::POST;
assert_eq!(request.method(), &Method::POST);
Source

pub fn set_method(&mut self, method: Method)

Sets the HTTP method for this request.

§Arguments
  • method - The new HTTP method
§Examples
use http_kit::Request;
use http::Method;

let mut request = Request::get("/api/users");
request.set_method(Method::PUT);
assert_eq!(request.method(), &Method::PUT);
Source

pub const fn uri(&self) -> &Uri

Returns a reference to the request URI.

§Examples
use http_kit::Request;

let request = Request::get("/api/users?page=1");
assert_eq!(request.uri().path(), "/api/users");
assert_eq!(request.uri().query(), Some("page=1"));
Source

pub fn uri_mut(&mut self) -> &mut Uri

Returns a mutable reference to the request URI.

§Examples
use http_kit::Request;

let mut request = Request::get("/api/users");
*request.uri_mut() = "/api/posts".parse().unwrap();
assert_eq!(request.uri().path(), "/api/posts");
Source

pub fn set_uri(&mut self, uri: Uri)

Sets the request URI.

§Arguments
  • uri - The new URI for the request
§Examples
use http_kit::Request;

let mut request = Request::get("/api/users");
request.set_uri("/api/posts".parse().unwrap());
assert_eq!(request.uri().path(), "/api/posts");
Source

pub const fn version(&self) -> Version

Returns the HTTP version for this request.

§Examples
use http_kit::Request;
use http::Version;

let request = Request::get("/api/users");
// Default version is typically HTTP/1.1
assert_eq!(request.version(), Version::HTTP_11);
Source

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

Returns a mutable reference to the HTTP version.

§Examples
use http_kit::Request;
use http::Version;

let mut request = Request::get("/api/users");
*request.version_mut() = Version::HTTP_2;
assert_eq!(request.version(), Version::HTTP_2);
Source

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

Sets the HTTP version for this request.

§Arguments
  • version - The HTTP version to use
§Examples
use http_kit::Request;
use http::Version;

let mut request = Request::get("/api/users");
request.set_version(Version::HTTP_2);
assert_eq!(request.version(), Version::HTTP_2);
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 request.

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

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

let request = Request::get("/api/users")
    .header(http::header::ACCEPT, "application/json")
    .header(http::header::USER_AGENT, "MyApp/1.0");
Source

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

Returns a reference to the HTTP headers.

§Examples
use http_kit::Request;

let request = Request::get("/api/users")
    .header(http::header::ACCEPT, "application/json");

let headers = request.headers();
assert!(headers.contains_key(http::header::ACCEPT));
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::Request;

let mut request = Request::get("/api/users");
request.headers_mut().insert(
    http::header::ACCEPT,
    "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::Request;

let request = Request::get("/api/users")
    .header(http::header::ACCEPT, "application/json");

if let Some(accept) = request.get_header(http::header::ACCEPT) {
    assert_eq!(accept, "application/json");
}
Source

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

Returns an iterator over all values for a header name.

This method retrieves all values for a specific header, unlike get_header which only returns the first value. This is useful for headers that can have multiple values like Accept or Set-Cookie.

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

let mut request = Request::get("/api/users");
request.append_header(http::header::ACCEPT, "text/html".parse().unwrap());
request.append_header(http::header::ACCEPT, "application/json".parse().unwrap());

// Iterate over all Accept header values
for accept in request.get_headers(http::header::ACCEPT) {
    println!("Accept: {}", accept.to_str().unwrap());
}
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::Request;

let mut request = Request::get("/api/users");
request.append_header(http::header::ACCEPT, "application/json".parse().unwrap());
request.append_header(http::header::ACCEPT, "text/html".parse().unwrap());
// Now the Accept header has both values
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::Request;

let mut request = Request::get("/api/users");
let old_value = request.insert_header(
    http::header::USER_AGENT,
    "MyApp/1.0".parse().unwrap()
);
assert!(old_value.is_none());

let old_value = request.insert_header(
    http::header::USER_AGENT,
    "MyApp/2.0".parse().unwrap()
);
assert!(old_value.is_some());
Source

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

Returns a reference to the request extensions.

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

§Examples
use http_kit::Request;

let request = Request::get("/api/users");
let extensions = request.extensions();
// Check if a specific type is stored
let user_id: Option<&u32> = extensions.get();
Source

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

Returns a mutable reference to the request extensions.

This allows modification of the extensions map.

§Examples
use http_kit::Request;

let mut request = Request::get("/api/users");
request.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::Request;

let mut request = Request::get("/api/users");
request.insert_extension(42u32);

if let Some(value) = request.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::Request;

let mut request = Request::get("/api/users");
request.insert_extension(42u32);

if let Some(value) = request.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::Request;

let mut request = Request::get("/api/users");
request.insert_extension(42u32);

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

let removed_again = request.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::Request;

let mut request = Request::get("/api/users");

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

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

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

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

This method extracts the body from the request 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::Request;

let mut request = Request::post("/api/data");
request.replace_body("Hello, world!");

let body = request.take_body()?;
// request.take_body() would now return an error
Source

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

Replaces the request 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::Request;

let mut request = Request::post("/api/data");
request.replace_body("Original content");

let old_body = request.replace_body("New content");
// old_body contains "Original content"
// request now contains "New content"
Source

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

Swaps the request body with another body.

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

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

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

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

let mut request = Request::post("/api/data");
request.replace_body("Request content");

let mut other_body = Body::from_bytes("Other content");
request.swap_body(&mut other_body)?;

// Now request contains "Other content"
// and other_body contains "Request content"
Source

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

Transforms the request body using the provided function.

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

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

let request = Request::post("/api/data")
    .map_body(|body| {
        // Transform empty body to contain JSON
        Body::from_bytes(r#"{"message": "Hello"}"#)
    });
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 request 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::Request;
use serde::Serialize;

#[derive(Serialize)]
struct User { name: String, age: u32 }

let user = User { name: "Alice".to_string(), age: 30 };
let request = Request::post("/api/users").json(&user)?;
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 request 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::Request;
use serde::Serialize;

#[derive(Serialize)]
struct LoginForm { username: String, password: String }

let form = LoginForm {
    username: "alice".to_string(),
    password: "secret".to_string(),
};
let request = Request::post("/login").form(&form)?;
Source

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

Consumes the request body and returns its data as bytes.

This method takes the request 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::Request;

let mut request = Request::post("/api/data");
request.replace_body("Hello, world!");

let bytes = request.into_bytes().await?;
assert_eq!(bytes, "Hello, world!");
Source

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

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

This method takes the request 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::Request;

let mut request = Request::post("/api/echo");
request.replace_body("Hello, world!");

let text = request.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 request body as JSON into the specified type.

This method reads the request 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 endpoints.

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::Request;
use serde::Deserialize;

#[derive(Deserialize)]
struct User { name: String, age: u32 }

let json_data = r#"{"name": "Alice", "age": 30}"#;
let mut request = Request::post("/api/users")
    .header(http::header::CONTENT_TYPE, "application/json");
request.replace_body(json_data);

let user: User = request.into_json().await?;
assert_eq!(user.name, "Alice");
Source

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

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

This method reads the request 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::Request;
use serde::Deserialize;

#[derive(Deserialize)]
struct LoginForm { username: String, password: String }

let form_data = "username=alice&password=secret";
let mut request = Request::post("/login")
    .header(http::header::CONTENT_TYPE, "application/x-www-form-urlencoded");
request.replace_body(form_data);

let form: LoginForm = request.into_form().await?;
assert_eq!(form.username, "alice");
Source

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

Sets the MIME type for the request.

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::Request;
use mime;

let request = Request::post("/api/data")
    .mime(mime::APPLICATION_JSON);
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::Request;
use mime;

let request = Request::post("/api/data")
    .header(http::header::CONTENT_TYPE, "application/json; charset=utf-8");

if let Some(mime_type) = request.get_mime() {
    assert_eq!(mime_type.type_(), mime::APPLICATION);
    assert_eq!(mime_type.subtype(), mime::JSON);
}

Trait Implementations§

Source§

impl Debug for Request

Source§

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

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

impl From<Request<Body>> for Request

Source§

fn from(request: Request<Body>) -> Self

Converts to this type from the input type.
Source§

impl From<Request> for Request<Body>

Source§

fn from(request: Request) -> 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.