use joist::{Config, Json, Plugin, RequestLog, Response, Router, Server, Status};
struct Health;
impl Plugin for Health {
fn name(&self) -> &'static str {
"health"
}
fn install(self: Box<Self>, router: &mut Router, config: &Config) {
let service = config.get_or("service.name", "hello").to_string();
router.get("/healthz", move |_| {
Response::json(&Json::object(vec![
("status", Json::from("ok")),
("service", Json::from(service.clone())),
("version", Json::from(joist::VERSION)),
]))
});
}
}
fn main() {
let mut config = Config::from_env("APP_");
config.set("service.name", "hello");
let mut router = Router::new();
router.get("/hello/:name", |req| {
Response::text(format!("hello {}", req.param("name").unwrap_or("world")))
});
router.post("/echo", |req| match req.json() {
Ok(value) => Response::json(&value),
Err(err) => Response::error(Status::BAD_REQUEST, &err.to_string()),
});
router.get("/search", |req| {
let query = req.query_param("q").unwrap_or_default();
Response::json(&Json::object(vec![("query", Json::from(query))]))
});
let address = format!(
"{}:{}",
config.get_or("host", "127.0.0.1"),
config.int("port").unwrap_or(8080)
);
let server = Server::new(router)
.config(config)
.with(RequestLog)
.plugin(Health)
.bind(&address)
.expect("bind");
println!("listening on http://{}", server.addr());
server.wait();
}