use salvo::prelude::*;
use salvo_extra::serve::StaticDir;

#[fn_handler]
async fn hello_world(req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    let mut output = String::with_capacity(1024);
    output.push_str(&format!("request: {:#?}", req));
    res.render_plain_text(&output);
}

#[fn_handler]
async fn print_json(res: &mut Response) {
    res.render_json_text("{\"data\": \"hello\"}\n")
}

#[fn_handler]
async fn send_redirect(res: &mut Response) {
    res.redirect_temporary("https://hatter.ink/");
}

#[tokio::main]
async fn main() {
    let router = Router::new().push(
        Router::new().get(hello_world)
    ).push(
        Router::new().path("json").get(print_json)
    ).push(
        Router::new().path("redirect").get(send_redirect)
    ).push(
        Router::new().path("files/<**path>").get(StaticDir::new("target"))
    );
    let server = Server::new(router);
    println!("Listen 0.0.0.0:7878...");
    server.bind(([0, 0, 0, 0], 7878)).await;
}
