1use joist::{Config, Json, Plugin, RequestLog, Response, Router, Server, Status};
8
9struct 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 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}