http_adapter/
http_adapter.rs

1// An example that uses the HttpHandler, an adapter that converts Unit's Request
2// and Response objects into types from the `http` crate.
3
4use http::{Request, Response};
5use unit_rs::{http::HttpHandler, Unit};
6
7fn main() {
8    let mut unit = Unit::new().unwrap();
9
10    unit.set_request_handler(HttpHandler::new(|req: Request<Vec<u8>>| {
11        let body = format!("Hello world!\n\nBody length: {}\n", req.body().len());
12
13        // The Unit server redirects stdout/stderr to the server log.
14        eprintln!("Received reqest for: {}", req.uri().path());
15
16        if req.uri().path() == "/panic" {
17            // The HttpHandler converts panics into 501 errors. This imposes an
18            // UnwindSafe restriction on the request handler.
19            panic!("The /panic path panics!")
20        }
21
22        let response = Response::builder()
23            .header("Content-Type", "text/plain")
24            .body(body.into_bytes())
25            .unwrap();
26
27        Ok(response)
28    }));
29
30    unit.run();
31}