joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
//! A small service showing routing, JSON, middleware and a plugin.
//!
//!     cargo run --example hello
//!     curl localhost:8080/hello/martin
//!     curl -X POST localhost:8080/echo -d '{"a":1}'

use joist::{Config, Json, Plugin, RequestLog, Response, Router, Server, Status};

/// Plugins bundle routes so an application can compose them.
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))]))
    });

    // Host is configurable so the same binary works on a laptop and in a
    // container, where binding to 127.0.0.1 would be unreachable from outside.
    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();
}