Skip to main content

hello/
hello.rs

1//! A small service showing routing, JSON, middleware and a plugin.
2//!
3//!     cargo run --example hello
4//!     curl localhost:8080/hello/martin
5//!     curl -X POST localhost:8080/echo -d '{"a":1}'
6
7use joist::{Config, Json, Plugin, RequestLog, Response, Router, Server, Status};
8
9/// Plugins bundle routes so an application can compose them.
10struct Health;
11
12impl Plugin for Health {
13    fn name(&self) -> &'static str {
14        "health"
15    }
16
17    fn install(self: Box<Self>, router: &mut Router, config: &Config) {
18        let service = config.get_or("service.name", "hello").to_string();
19        router.get("/healthz", move |_| {
20            Response::json(&Json::object(vec![
21                ("status", Json::from("ok")),
22                ("service", Json::from(service.clone())),
23                ("version", Json::from(joist::VERSION)),
24            ]))
25        });
26    }
27}
28
29fn main() {
30    let mut config = Config::from_env("APP_");
31    config.set("service.name", "hello");
32
33    let mut router = Router::new();
34
35    router.get("/hello/:name", |req| {
36        Response::text(format!("hello {}", req.param("name").unwrap_or("world")))
37    });
38
39    router.post("/echo", |req| match req.json() {
40        Ok(value) => Response::json(&value),
41        Err(err) => Response::error(Status::BAD_REQUEST, &err.to_string()),
42    });
43
44    router.get("/search", |req| {
45        let query = req.query_param("q").unwrap_or_default();
46        Response::json(&Json::object(vec![("query", Json::from(query))]))
47    });
48
49    // Host is configurable so the same binary works on a laptop and in a
50    // container, where binding to 127.0.0.1 would be unreachable from outside.
51    let address = format!(
52        "{}:{}",
53        config.get_or("host", "127.0.0.1"),
54        config.int("port").unwrap_or(8080)
55    );
56
57    let server = Server::new(router)
58        .config(config)
59        .with(RequestLog)
60        .plugin(Health)
61        .bind(&address)
62        .expect("bind");
63
64    println!("listening on http://{}", server.addr());
65    server.wait();
66}