Skip to main content

rust_web_server/controller/
mod.rs

1//! Controllers: one unit of request handling for [`App`](crate::app::App).
2//!
3//! A [`Controller`] answers two questions: `is_matching(request, connection)` —
4//! does this request belong to me? — and `process(request, response, connection)`
5//! — produce the response. `App::execute` asks each built-in controller in order
6//! and uses the first match. `is_matching` runs for every request, so keep it
7//! cheap and silent (check the method before the path).
8//!
9//! The server can't recover from errors inside a controller, so `process` must
10//! turn failures into a response itself (e.g. a `500`). `src/controller/example/`
11//! has an `IndexController` that serves `index.html` from the working directory,
12//! falling back to a page compiled into the binary with `include_bytes!`.
13
14#[cfg(test)]
15mod example;
16
17use crate::request::Request;
18use crate::response::Response;
19use crate::server::ConnectionInfo;
20
21/// Core routing and handling trait. Implement this to add a route to the server.
22///
23/// # Example
24///
25/// ```rust,no_run
26/// use rust_web_server::controller::Controller;
27/// use rust_web_server::request::{METHOD, Request};
28/// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
29/// use rust_web_server::range::Range;
30/// use rust_web_server::mime_type::MimeType;
31/// use rust_web_server::server::ConnectionInfo;
32///
33/// pub struct HelloController;
34///
35/// impl Controller for HelloController {
36///     fn is_matching(request: &Request, _: &ConnectionInfo) -> bool {
37///         request.method == METHOD.get && request.request_uri == "/hello"
38///     }
39///
40///     fn process(_: &Request, mut response: Response, _: &ConnectionInfo) -> Response {
41///         response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
42///         response.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
43///         response.content_range_list = vec![
44///             Range::get_content_range(b"Hello!".to_vec(), MimeType::TEXT_PLAIN.to_string())
45///         ];
46///         response
47///     }
48/// }
49/// ```
50pub trait Controller {
51    /// Returns `true` if this controller should handle the given request.
52    /// Called in declaration order; the first match wins.
53    fn is_matching(request: &Request, connection: &ConnectionInfo) -> bool;
54
55    /// Produces the response. Receives the partially-built `response` (already populated
56    /// with standard headers from [`Header::get_header_list`]) and must return it populated
57    /// with a status code and body.
58    fn process(request: &Request, response: Response, connection: &ConnectionInfo) -> Response;
59}