Response

Struct Response 

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

Represents an HTTP-like response.

Implementations§

Source§

impl Response

Source

pub fn new(status_code: u16) -> Self

Creates a new response with a given status code.

Examples found in repository?
examples/demo.rs (line 27)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let server = lazy_sock!("/tmp/lazy-sock-demo.sock");
8
9    // Route for GET /
10    server
11        .route(Method::Get, "/", |_req| {
12            Response::json(r#"{"message": "Hello, World!", "status": "success"}"#)
13        })
14        .await;
15
16    // Route for GET /health
17    server
18        .route(Method::Get, "/health", |_req| {
19            Response::json(r#"{"status": "healthy"}"#)
20        })
21        .await;
22
23    // Route for POST /echo
24    server
25        .route(Method::Post, "/echo", |req| match req.body_string() {
26            Ok(body) if !body.is_empty() => Response::json(&format!(r#"{{"echo": "{}"}}"#, body)),
27            Ok(_) => Response::new(400).with_text("Request body is empty"),
28            Err(_) => Response::new(400).with_text("Invalid UTF-8 in request body"),
29        })
30        .await;
31
32    // Route for GET /html
33    server
34        .route(Method::Get, "/html", |_req| {
35            Response::html(
36                r#"
37            <!DOCTYPE html>
38            <html>
39            <head><title>Lazy Sock Demo</title></head>
40            <body><h1>Hello from Lazy Sock!</h1></body>
41            </html>
42        "#,
43            )
44        })
45        .await;
46
47    println!("Lazy Sock Demo Server Starting...");
48    println!("Socket: /tmp/lazy-sock-demo.sock");
49    println!("Try these commands:");
50    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/");
51    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/health");
52    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/html");
53    println!(
54        "   curl --unix-socket /tmp/lazy-sock-demo.sock -X POST http://localhost/echo -d 'Hello from curl!'"
55    );
56    println!("Press Ctrl+C to stop");
57    println!();
58
59    // Run the server
60    server.run().await?;
61
62    println!("Server stopped gracefully.");
63    Ok(())
64}
Source

pub fn ok() -> Self

Creates a 200 OK response.

Source

pub fn not_found(message: &str) -> Self

Creates a 404 Not Found response.

Source

pub fn internal_error(message: &str) -> Self

Creates a 500 Internal Server Error response.

Source

pub fn with_header(self, name: &str, value: &str) -> Self

Adds a header to the response.

Source

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

Sets a plain text body for the response.

Examples found in repository?
examples/demo.rs (line 27)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let server = lazy_sock!("/tmp/lazy-sock-demo.sock");
8
9    // Route for GET /
10    server
11        .route(Method::Get, "/", |_req| {
12            Response::json(r#"{"message": "Hello, World!", "status": "success"}"#)
13        })
14        .await;
15
16    // Route for GET /health
17    server
18        .route(Method::Get, "/health", |_req| {
19            Response::json(r#"{"status": "healthy"}"#)
20        })
21        .await;
22
23    // Route for POST /echo
24    server
25        .route(Method::Post, "/echo", |req| match req.body_string() {
26            Ok(body) if !body.is_empty() => Response::json(&format!(r#"{{"echo": "{}"}}"#, body)),
27            Ok(_) => Response::new(400).with_text("Request body is empty"),
28            Err(_) => Response::new(400).with_text("Invalid UTF-8 in request body"),
29        })
30        .await;
31
32    // Route for GET /html
33    server
34        .route(Method::Get, "/html", |_req| {
35            Response::html(
36                r#"
37            <!DOCTYPE html>
38            <html>
39            <head><title>Lazy Sock Demo</title></head>
40            <body><h1>Hello from Lazy Sock!</h1></body>
41            </html>
42        "#,
43            )
44        })
45        .await;
46
47    println!("Lazy Sock Demo Server Starting...");
48    println!("Socket: /tmp/lazy-sock-demo.sock");
49    println!("Try these commands:");
50    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/");
51    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/health");
52    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/html");
53    println!(
54        "   curl --unix-socket /tmp/lazy-sock-demo.sock -X POST http://localhost/echo -d 'Hello from curl!'"
55    );
56    println!("Press Ctrl+C to stop");
57    println!();
58
59    // Run the server
60    server.run().await?;
61
62    println!("Server stopped gracefully.");
63    Ok(())
64}
Source

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

Sets a JSON body for the response.

Source

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

Sets an HTML body for the response.

Source

pub fn with_binary(self, data: Vec<u8>, content_type: &str) -> Self

Sets a binary body for the response.

Source

pub fn status_code(&self) -> u16

Gets the status code.

Source

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

Gets the response headers.

Source

pub fn body(&self) -> &[u8]

Gets the response body.

Source

pub fn to_http_response(&self) -> String

Converts the Response struct into a raw HTTP response string.

Source§

impl Response

Source

pub fn json(data: &str) -> Self

Creates a 200 OK response with a JSON body.

Examples found in repository?
examples/demo.rs (line 12)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let server = lazy_sock!("/tmp/lazy-sock-demo.sock");
8
9    // Route for GET /
10    server
11        .route(Method::Get, "/", |_req| {
12            Response::json(r#"{"message": "Hello, World!", "status": "success"}"#)
13        })
14        .await;
15
16    // Route for GET /health
17    server
18        .route(Method::Get, "/health", |_req| {
19            Response::json(r#"{"status": "healthy"}"#)
20        })
21        .await;
22
23    // Route for POST /echo
24    server
25        .route(Method::Post, "/echo", |req| match req.body_string() {
26            Ok(body) if !body.is_empty() => Response::json(&format!(r#"{{"echo": "{}"}}"#, body)),
27            Ok(_) => Response::new(400).with_text("Request body is empty"),
28            Err(_) => Response::new(400).with_text("Invalid UTF-8 in request body"),
29        })
30        .await;
31
32    // Route for GET /html
33    server
34        .route(Method::Get, "/html", |_req| {
35            Response::html(
36                r#"
37            <!DOCTYPE html>
38            <html>
39            <head><title>Lazy Sock Demo</title></head>
40            <body><h1>Hello from Lazy Sock!</h1></body>
41            </html>
42        "#,
43            )
44        })
45        .await;
46
47    println!("Lazy Sock Demo Server Starting...");
48    println!("Socket: /tmp/lazy-sock-demo.sock");
49    println!("Try these commands:");
50    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/");
51    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/health");
52    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/html");
53    println!(
54        "   curl --unix-socket /tmp/lazy-sock-demo.sock -X POST http://localhost/echo -d 'Hello from curl!'"
55    );
56    println!("Press Ctrl+C to stop");
57    println!();
58
59    // Run the server
60    server.run().await?;
61
62    println!("Server stopped gracefully.");
63    Ok(())
64}
Source

pub fn text(text: &str) -> Self

Creates a 200 OK response with a plain text body.

Source

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

Creates a 200 OK response with an HTML body.

Examples found in repository?
examples/demo.rs (lines 35-43)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let server = lazy_sock!("/tmp/lazy-sock-demo.sock");
8
9    // Route for GET /
10    server
11        .route(Method::Get, "/", |_req| {
12            Response::json(r#"{"message": "Hello, World!", "status": "success"}"#)
13        })
14        .await;
15
16    // Route for GET /health
17    server
18        .route(Method::Get, "/health", |_req| {
19            Response::json(r#"{"status": "healthy"}"#)
20        })
21        .await;
22
23    // Route for POST /echo
24    server
25        .route(Method::Post, "/echo", |req| match req.body_string() {
26            Ok(body) if !body.is_empty() => Response::json(&format!(r#"{{"echo": "{}"}}"#, body)),
27            Ok(_) => Response::new(400).with_text("Request body is empty"),
28            Err(_) => Response::new(400).with_text("Invalid UTF-8 in request body"),
29        })
30        .await;
31
32    // Route for GET /html
33    server
34        .route(Method::Get, "/html", |_req| {
35            Response::html(
36                r#"
37            <!DOCTYPE html>
38            <html>
39            <head><title>Lazy Sock Demo</title></head>
40            <body><h1>Hello from Lazy Sock!</h1></body>
41            </html>
42        "#,
43            )
44        })
45        .await;
46
47    println!("Lazy Sock Demo Server Starting...");
48    println!("Socket: /tmp/lazy-sock-demo.sock");
49    println!("Try these commands:");
50    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/");
51    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/health");
52    println!("   curl --unix-socket /tmp/lazy-sock-demo.sock http://localhost/html");
53    println!(
54        "   curl --unix-socket /tmp/lazy-sock-demo.sock -X POST http://localhost/echo -d 'Hello from curl!'"
55    );
56    println!("Press Ctrl+C to stop");
57    println!();
58
59    // Run the server
60    server.run().await?;
61
62    println!("Server stopped gracefully.");
63    Ok(())
64}

Trait Implementations§

Source§

impl Clone for Response

Source§

fn clone(&self) -> Response

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 Response

Source§

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

Formats the value using the given formatter. 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, 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<T> ErasedDestructor for T
where T: 'static,