Skip to main content

HttpResponse

Struct HttpResponse 

Source
pub struct HttpResponse {
    pub headers: ResponseHeaders,
    /* private fields */
}
Expand description

Represents an HTTP response being sent to the client.

The HttpResponse struct provides methods to construct and manipulate HTTP responses including status codes, headers, cookies, and different types of response bodies.

§Examples

Basic usage:

use ripress::context::HttpResponse;

let res = HttpResponse::new();
res.ok().text("Hello, World!");

JSON response:

use ripress::context::HttpResponse;
use serde_json::json;

let res = HttpResponse::new();
res.ok().json(json!({
    "message": "Success",
    "code": 200
}));

§Fields

  • status_code - HTTP status code (e.g., 200, 404, 500)
  • body - Response body content (JSON, text)
  • content_type - Content-Type header value
  • cookies - Response cookies to be set
  • headers - Response headers
  • remove_cookies - Cookies to be removed

Fields§

§headers: ResponseHeaders

Sets response headers

Implementations§

Source§

impl HttpResponse

Source

pub fn new() -> Self

Creates a new HTTP response with default values.

§Returns

Returns a new HttpResponse initialized with:

  • Status code: 200
  • Empty text body
  • JSON content type
  • Empty cookies and headers
§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new();
Source

pub fn ok(self) -> Self

Sets the status code to 200 OK.

Source

pub fn created(self) -> Self

Sets the status code to 201 Created.

Source

pub fn accepted(self) -> Self

Sets the status code to 202 Accepted.

Source

pub fn no_content(self) -> Self

Sets the status code to 204 No Content.

Source

pub fn bad_request(self) -> Self

Sets the status code to 400 Bad Request.

Source

pub fn unauthorized(self) -> Self

Sets the status code to 401 Unauthorized.

Source

pub fn forbidden(self) -> Self

Sets the status code to 403 Forbidden.

Source

pub fn not_found(self) -> Self

Sets the status code to 404 Not Found.

Source

pub fn method_not_allowed(self) -> Self

Sets the status code to 405 Method Not Allowed.

Source

pub fn conflict(self) -> Self

Sets the status code to 409 Conflict.

Source

pub fn internal_server_error(self) -> Self

Sets the status code to 500 Internal Server Error.

Source

pub fn not_implemented(self) -> Self

Sets the status code to 501 Not Implemented.

Source

pub fn bad_gateway(self) -> Self

Sets the status code to 502 Bad Gateway.

Source

pub fn service_unavailable(self) -> Self

Sets the status code to 503 Service Unavailable.

Source

pub fn status(self, status_code: u16) -> Self

Sets the status code to a given u16 value.

Source

pub fn status_code(&self) -> u16

Returns the current HTTP status code as a u16.

Source

pub fn text<T: Into<String>>(self, text: T) -> Self

Sets the response body to text.

§Arguments
  • text - Any type that can be converted into a String
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new()
    .ok()
    .text("Operation completed successfully");

// Using with different types
let res = HttpResponse::new()
    .ok()
    .text(format!("Count: {}", 42));
Source

pub fn json<T: Serialize>(self, json: T) -> Self

Sets the response body to JSON.

§Arguments
  • json - Any type that implements serde::Serialize
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;
use serde::Serialize;

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

let user = User {
    name: "John".to_string(),
    age: 30,
};

let res = HttpResponse::new()
    .ok()
    .json(user);
Source

pub fn bytes<T: Into<Bytes>>(self, bytes: T) -> Self

Sets the response body to binary data.

§Arguments
  • bytes - Any type that can be converted into Bytes
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;
use bytes::Bytes;

let data = vec![1, 2, 3, 4, 5];

let res = HttpResponse::new()
    .ok()
    .bytes(data);

// Using with Bytes directly
let res = HttpResponse::new()
    .ok()
    .bytes(Bytes::from_static(b"hello world"));
Source

pub fn set_header<K, V>(self, header_name: K, header_value: V) -> Self
where K: Into<String>, V: Into<String>,

Sets a header in the response.

§Example
use ripress::context::HttpResponse;

use ripress::context::HttpResponse; let res = HttpResponse::new(); res.set_header(“key”, “value”); // Sets the key cookie to value

Sets a cookie in the response.

§Arguments
  • key - The name of the cookie
  • value - The value to set
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;
use ripress::res::response_cookie::CookieOptions;

let res = HttpResponse::new()
    .set_cookie("session", "abc123", None)
    .ok()
    .text("Logged in");

Removes a cookie from the response.

§Arguments
  • key - The name of the cookie to remove
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new()
    .clear_cookie("session")
    .ok()
    .text("Logged out");
Source

pub fn redirect(self, path: &'static str) -> Self

Redirects the client to the specified URL.

§Arguments
  • url - The url to redirect to
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new();
res.redirect("https://www.example.com");
Source

pub fn permanent_redirect(self, path: &'static str) -> Self

Permanently redirects the client to the specified URL.

§Arguments
  • url - The url to redirect to
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new();
res.permanent_redirect("https://www.example.com");
Source

pub fn html(self, html: &str) -> Self

Sets the response body to html.

§Arguments
  • html_content - Any type that can be converted into a String
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;

let res = HttpResponse::new()
    .ok()
    .html("<h1>Hello, World!</h1>");

// Using with different types
let res = HttpResponse::new()
    .ok()
    .text(format!("<h1>Count: {}</h1>", 42));
Source

pub async fn send_file(self, path: &'static str) -> Self

Sends the contents of a file as the response body. This method reads the file at the given path asynchronously and sets the response body to its contents. The content type is inferred from the file’s bytes using the infer crate and then mapped to a MIME type via mime_guess. If the type cannot be determined, it falls back to application/octet-stream.

§Arguments
  • path - The path to the file to be sent. Must be a static string slice.
§Returns

Returns Self for method chaining.

§Example
use ripress::context::HttpResponse;
use ripress::context::HttpRequest;

async fn handler(req: HttpRequest, res: HttpResponse) -> HttpResponse {
    // Send a file as the response
    res.ok().send_file("static/image.png").await
}
Source

pub fn write<S, E>(self, stream: S) -> Self
where S: Stream<Item = Result<Bytes, E>> + Send + 'static, E: Into<HttpResponseError> + Send + 'static,

Streams the response

§Arguments
  • stream - The stream to stream
§Returns

Returns Self for method chaining

§Example
use ripress::context::HttpResponse;
use bytes::Bytes;
use futures::stream;
use futures::StreamExt;

let res = HttpResponse::new();

let stream = stream::iter(0..5).map(|n| Ok::<Bytes, std::io::Error>(Bytes::from(format!("Number: {}\n", n))));

res.write(stream);

Trait Implementations§

Source§

impl Clone for HttpResponse

Source§

fn clone(&self) -> Self

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 HttpResponse

Source§

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

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

impl Default for HttpResponse

Source§

fn default() -> Self

Returns the “default value” for a type. 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