Skip to main content

Response

Struct Response 

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

Represents the response object that will be sent to the client

In Krustie, reponse objects doesn’t need to be returned and created. Instead they need to be modified using methods.

The basic functions to create a response are: status, headers, body and body_json.

  • status sets the status code of the response. It takes StatusCode as an argument.
  • headers extends the current headers of the response. It takes a HashMap<string, string> as an argument.
    • If you want to add just a single header there is the Response::set_header function which takes two strings, a key and a value, as an argument.
  • body sets the body of the response. It takes a Vec<u8> and a [ContentType] as arguments.
  • body_json sets the body of the response as a JSON object. It takes a serde_json::Value as an argument.

Response can be basicaly built by using the status, headers and body functions which can be chained like this:


fn get(request: &Request, response: &mut Response) {
  let mut headers = HashMap::new();

  headers.insert("Server".to_string(), "Krustie".to_string());

  response
    .status(StatusCode::Ok)
    .headers(headers)
    .body(b"Hello, World!".to_vec(), ContentType::Text);
}

But there are other functions such as Response::set_header and Response::set_body can be useful especially when creating a middleware.

Implementations§

Source§

impl Response

Source

pub fn body(&mut self, body: Vec<u8>, content_type: ContentType) -> &mut Self

Sets the body of the response. Function sets Content-Length automatically but needs Content-Type to be set manually.

If Content-Type is not set, it defaults to text/plain.

§Example
use krustie::{ Response, StatusCode, Request, response::ContentType, json::json };

fn get(request: &Request, response: &mut Response) {
    response.body(b"Hello, World!".to_vec(), ContentType::Text);
}
use krustie::{ Response, StatusCode, Request, response::ContentType, json::json };

fn get(request: &Request, response: &mut Response) {
   response.status(StatusCode::Ok).body(b"<html><body><h1>Hello, World!</h1></body></html>".to_vec(), ContentType::Html);
}
Source

pub fn body_raw(&mut self, body: Vec<u8>, mime: &str) -> &mut Self

Sets the body of the response. Function sets Content-Length automatically but needs Content-Type to be set manually.

If Content-Type is not set, it defaults to text/plain.

§Example
use krustie::{ Response, StatusCode, Request, response::ContentType, json::json };

fn get(request: &Request, response: &mut Response) {
    response.body(b"Hello, World!".to_vec(), ContentType::Text);
}
use krustie::{ Response, StatusCode, Request, response::ContentType, json::json };

fn get(request: &Request, response: &mut Response) {
   response.status(StatusCode::Ok).body_raw(b"<html><body><h1>Hello, World!</h1></body></html>".to_vec(), "text/html");
}
Source

pub fn body_text(&mut self, text: &str) -> &mut Self

Sets the body of the response to a Text value.

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: &mut Response) {
   response.body_text("Hello, World!");
}
Examples found in repository?
examples/simple.rs (line 8)
3async fn main() {
4    let mut server = krustie::Server::create();
5    let mut router = krustie::Router::new();
6
7    router.get("/", |_, res| {
8        res.status(krustie::StatusCode::Ok).body_text("Hello World!");
9    });
10
11    server.use_handler(router);
12
13    server.listen(8080).await;
14}
Source

pub fn body_json(&mut self, data: JsonValue) -> &mut Self

Sets the body of the response to a JSON value.

§Example
use krustie::{ Response, StatusCode, Request, json::json };

fn get(request: &Request, response: &mut Response) {
   response.body_json(json!({"message": "Hello, World!"}));
}
Source§

impl Response

Source

pub fn assert_eq(resp1: &Response, resp2: &Response)

Compares two responses and asserts that they are equal

§Example
use krustie::Response;

let response1 = Response::default();
let response2 = Response::default();

Response::assert_eq(&response1, &response2);
Source§

impl Response

Source

pub fn get_headers(&self) -> &HashMap<String, String>

Gets the headers of the response

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: Response) {
  let headers = response.get_headers();

  for (key, value) in headers.iter() {
    println!("{}: {}", key, value);
  }
}
Source

pub fn get_header(&self, key: &str) -> Option<&String>

Gets requested header from the response

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: Response) {
  let server_header = response.get_header("Server");

  match server_header {
    Some(header) => println!("Server header: {}", header),
    None => println!("Server header not found")
  }
}
Source

pub fn set_header(&mut self, key: &str, value: &str) -> &mut Self

Adds a single header to the response

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: &mut Response) {
  response.set_header("Server", "Krustie");
}
Source

pub fn get_body(&self) -> &Vec<u8>

Gets the body of the response as a byte vector reference

§Example
use krustie::{ Response, StatusCode, Request, json::json };

fn get(request: &Request, response: &mut Response) {
  let body = response.get_body();
}
Source

pub fn get_body_mut(&mut self) -> &mut Vec<u8>

Gets the body of the response as a mutable byte vector reference

§Example
use krustie::{ Response, StatusCode, Request, json::json };

fn get(request: &Request, response: &mut Response) {
  let body = response.get_body_mut();
}
Source

pub fn set_body(&mut self, body: Vec<u8>) -> Result<(), String>

Updates the body of the response.

Function sets Content-Length automatically but needs Content-Type to be set manually.

§Errors

Returns an error if the request has no body already.

§Example
use krustie::{ Response, StatusCode, Request, response::ContentType, json::json };

fn get(request: &Request, response: &mut Response) {
  response.body(b"Hello, World!".to_vec(), ContentType::Text);

  response.set_body(b"Goodbye, Mars!".to_vec());
}
Source

pub fn get_local(&self, key: &str) -> Option<&String>

Returns the value of the local variable

Local variables can be used to store data that can be defined in a middleware and accessed in the controller

§Example
use krustie::{ Request, Response };

fn get(request: &Request, response: &mut Response) {
   let user_id = response.get_local("user_id");
}
Source

pub fn set_local(&mut self, key: &str, value: &str) -> Option<String>

Adds a local variable to the http request

Local variables can be used to store data that can be defined in a middleware and accessed in the controller

§Example
use krustie::{ Request, Response };

fn get(request: &Request, response: &mut Response) {
  response.set_local("user_id", "123");
}
Source

pub fn get_status(&self) -> StatusCode

Returns the status code of the response

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: Response) {
  let status_code = response.get_status();
}
Source

pub fn is_error(&self) -> bool

Returns true if status code is 4xx or 5xx.

Source§

impl Response

Source

pub fn status(&mut self, status_code: StatusCode) -> &mut Self

Sets the status of the response

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: &mut Response) {
   response.status(StatusCode::Ok);
}
Examples found in repository?
examples/simple.rs (line 8)
3async fn main() {
4    let mut server = krustie::Server::create();
5    let mut router = krustie::Router::new();
6
7    router.get("/", |_, res| {
8        res.status(krustie::StatusCode::Ok).body_text("Hello World!");
9    });
10
11    server.use_handler(router);
12
13    server.listen(8080).await;
14}
Source

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

Adds headers to the response

§Example

Add Server: Rust and Connection: close headers to the response.

use krustie::{ Response, StatusCode, Request };
use std::collections::HashMap;

fn get(request: &Request, response: &mut Response) {
    let mut headers = HashMap::new();

    headers.insert("Server".to_string(), "Krustie".to_string());
    headers.insert("Connection".to_string(), "close".to_string());

    response.status(StatusCode::Ok).headers(headers);
}

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 Default for Response

Source§

fn default() -> Self

Returns a default instance of Response

§Example
use krustie::response::Response;

let response = Response::default();
Source§

impl From<Response> for Vec<u8>

Source§

fn from(response: Response) -> Vec<u8>

Returns the response as a byte vector.

§Example
use krustie::{ Response, StatusCode, Request };

fn get(request: &Request, response: Response) {
  let response_bytes: Vec<u8> = response.into();
}
Source§

impl ToString for Response

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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> 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.