Skip to main content

HttpRequest

Struct HttpRequest 

Source
pub struct HttpRequest {
    pub params: RouteParams,
    pub query: QueryParams,
    pub origin_url: Url,
    pub method: HttpMethods,
    pub path: String,
    pub protocol: String,
    pub headers: RequestHeaders,
    /* private fields */
}
Expand description

Represents an incoming HTTP request with comprehensive access to request data.

The HttpRequest struct provides methods to access and manipulate all aspects of an HTTP request including headers, cookies, query parameters, route parameters, and request body content.

§Examples

Basic usage:

use ripress::req::HttpRequest;

let req = HttpRequest::new();
println!("Method: {:?}", req.method);
println!("Path: {}", req.path);
println!("Client IP: {:?}", req.ip());

Working with JSON body:

use ripress::context::HttpRequest;
use serde::{Deserialize, Serialize};

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

let req = HttpRequest::new();
if let Ok(user) = req.json::<User>() {
    println!("User: {} is {} years old", user.name, user.age);
}

Fields§

§params: RouteParams

Dynamic route parameters extracted from the URL.

§query: QueryParams

Query parameters from the request URL.

§origin_url: Url

The full URL of the incoming request.

§method: HttpMethods

The HTTP method used for the request (e.g., GET, POST, PUT, DELETE).

§path: String

The requested endpoint path.

§protocol: String

Protocol of the request (HTTP or HTTPs)

§headers: RequestHeaders

The request’s headers

Implementations§

Source§

impl HttpRequest

Source

pub fn new() -> Self

Creates a new empty HTTP request instance.

§Returns

Returns a new HttpRequest with default values.

§Example
use ripress::req::HttpRequest;
use ripress::types::HttpMethods;

let req = HttpRequest::new();
assert_eq!(req.method, HttpMethods::GET);

Retrieves a cookie value by name.

§Arguments
  • name - The name of the cookie to retrieve
§Returns

Returns Some(&String) with the cookie value if found, or None if not found.

§Example
use ripress::context::HttpRequest;

let req = HttpRequest::new();

match req.get_cookie("session_id") {
    Some(session) => println!("Session ID: {}", session),
    None => println!("No session cookie found")
}
Source

pub fn xhr(&self) -> bool

Returns true if the request is an XMLHttpRequest.

Source

pub fn is_secure(&self) -> bool

Returns true if the request is secure.

Source

pub fn ip(&self) -> IpAddr

Returns the client’s IP address.

Source

pub fn set_data<T: Into<String>>(&mut self, data_key: T, data_value: T)

Adds data from the middleware into the request.

§Arguments
  • key - The key of the data to retrieve
  • value - The value of the data to retrieve
§Example
let mut req = ripress::req::HttpRequest::new();
req.set_data("id", "123");
let id = req.get_data("id");
println!("Id: {:?}", id);
Source

pub fn get_all_data(&self) -> &RequestData

Returns all data stored in the request by the middleware.

§Returns

Returns &HashMap<String, String> with the data.

§Example
let req = ripress::req::HttpRequest::new();

let data = req.get_all_data();

println!("Data: {}", data);
Source

pub fn get_data<T: Into<String>>(&self, data_key: T) -> Option<String>

Returns data stored in the request by the middleware.

§Arguments
  • key - The key of the data to retrieve
§Returns

Returns Option<&String> with the data value if found, or None if not found.

§Example
let req = ripress::context::HttpRequest::new();
let id = req.get_data("id");
println!("Id: {:?}", id);
Source

pub fn is(&self, content_type: RequestBodyType) -> bool

Checks if the request body matches a specific content type.

§Arguments
  • content_type - The RequestBodyType to check against
§Returns

Returns true if the content type matches, false otherwise.

§Example
use ripress::req::HttpRequest;
use ripress::req::body::RequestBodyType;

let req = HttpRequest::new();
if req.is(RequestBodyType::JSON) {
    // Handle JSON content
}
Source

pub fn bytes(&self) -> Result<&[u8], String>

Returns a read-only view of the raw request body when it is binary.

Returns:

  • Ok(&[u8]) when content_type is RequestBodyType::BINARY.
  • Err("Invalid Binary Content") if the internal variant does not match the declared type.
  • Err(...) describing the actual content type if it is not binary.
§Example
let req = ripress::context::HttpRequest::new();
if let Ok(bytes) = req.bytes() {
    // process bytes...
}
Source

pub fn json<J>(&self) -> Result<J, String>

Deserializes the request body as JSON into the specified type.

§Type Parameters
  • J - The type to deserialize into, must implement DeserializeOwned
§Returns

Returns Ok(J) with the deserialized value if successful, or Err(String) with an error message if deserialization fails.

§Example
use ripress::context::HttpRequest;
use serde::{Deserialize, Serialize};

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

let req = HttpRequest::new();
match req.json::<LoginData>() {
    Ok(data) => println!("Login attempt for: {}", data.username),
    Err(e) => println!("Invalid login data: {}", e)
}
Source

pub fn text(&self) -> Result<&str, String>

Returns request’s text body.

§Example
let req = ripress::req::HttpRequest::new();
let text = req.text().unwrap();
println!("text : {:?}", text);

This function returns the text body of the request. Returns an Result<String>, where Ok(String) contains the body if it is valid text, or Err(error) if it is not.

Source

pub fn form_data(&self) -> Result<&FormData, String>

Returns request’s form_data body.

§Example
let req = ripress::req::HttpRequest::new();
// Let' say form data was sent as key=value and key2=value2
let form_data = req.form_data().unwrap();
println!("key = : {:?}", form_data.get("key"));
println!("key2 = : {:?}", form_data.get("key2"));

This function returns a HashMap of the form data. Returns an Result<HashMap<String, String>>, where Ok(HashMap<String, String>) contains the form_data if it is valid form data, or Err(error) if it is not.

Source

pub fn insert_form_field(&mut self, key: &str, value: &str)

Inserts a key-value pair into the request’s form data.

If the current body is not FORM, this will initialize an empty FormData and set the body’s content type to FORM before inserting the field. This is useful for middlewares that wish to expose computed values through the form_data() API, such as attaching file upload metadata.

Trait Implementations§

Source§

impl Clone for HttpRequest

Source§

fn clone(&self) -> HttpRequest

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 HttpRequest

Source§

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

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

impl Default for HttpRequest

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl ExtractFromOwned for HttpRequest

Source§

type Error = Infallible

The associated error type returned when extraction fails.
Source§

fn extract_from_owned(req: HttpRequest) -> Result<Self, Self::Error>

Extract the parameter from an owned HttpRequest. 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<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