rws_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/// # extern crate rws_server as rust_web_server;
27/// use rust_web_server::controller::Controller;
28/// use rust_web_server::request::{METHOD, Request};
29/// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
30/// use rust_web_server::range::Range;
31/// use rust_web_server::mime_type::MimeType;
32/// use rust_web_server::server::ConnectionInfo;
33///
34/// pub struct HelloController;
35///
36/// impl Controller for HelloController {
37/// fn is_matching(request: &Request, _: &ConnectionInfo) -> bool {
38/// request.method == METHOD.get && request.request_uri == "/hello"
39/// }
40///
41/// fn process(_: &Request, mut response: Response, _: &ConnectionInfo) -> Response {
42/// response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
43/// response.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
44/// response.content_range_list = vec![
45/// Range::get_content_range(b"Hello!".to_vec(), MimeType::TEXT_PLAIN.to_string())
46/// ];
47/// response
48/// }
49/// }
50/// ```
51pub trait Controller {
52 /// Returns `true` if this controller should handle the given request.
53 /// Called in declaration order; the first match wins.
54 fn is_matching(request: &Request, connection: &ConnectionInfo) -> bool;
55
56 /// Produces the response. Receives the partially-built `response` (already populated
57 /// with standard headers from [`Header::get_header_list`]) and must return it populated
58 /// with a status code and body.
59 fn process(request: &Request, response: Response, connection: &ConnectionInfo) -> Response;
60}