request_info/
request_info.rs

1// An example inspired by the official example application written in C:
2// https://github.com/nginx/unit/blob/bba97134e9/src/test/nxt_unit_app_test.c
3
4use std::io::Write;
5
6use unit_rs::{Request, Unit, UnitResult};
7
8fn main() {
9    let mut unit = Unit::new().unwrap();
10
11    unit.set_request_handler(request_handler);
12
13    unit.run();
14}
15
16fn request_handler(req: Request) -> UnitResult<()> {
17    // Create and send a response.
18    let headers = &[("Content-Type", "text/plain")];
19    req.send_response(200, headers, "Hello world!\n")?;
20
21    // NGINX Unit uses "Transfer-Encoding: chunked" by default, and can send
22    // additional chunks after the initial response was already sent to the
23    // client.
24    req.send_chunks_with_writer(4096, |w| {
25        write!(w, "Request data:\n")?;
26        write!(w, "  Method: {}\n", req.method())?;
27        write!(w, "  Protocol: {}\n", req.version())?;
28        write!(w, "  Remote addr: {}\n", req.remote())?;
29        write!(w, "  Local addr: {}\n", req.local())?;
30        write!(w, "  Server name: {}\n", req.server_name())?;
31        write!(w, "  Target: {}\n", req.target())?;
32        write!(w, "  Path: {}\n", req.path())?;
33        write!(w, "  Query: {}\n", req.query())?;
34        write!(w, "  Fields:\n")?;
35        for (name, value) in req.fields() {
36            write!(w, "    {}: {}\n", name, value).unwrap();
37        }
38        write!(w, "  Body:\n    ").unwrap();
39
40        w.copy_from_reader(req.body())?;
41
42        Ok(())
43    })?;
44
45    Ok(())
46}