kochab/examples/routing.rs

57 lines
1.7 KiB
Rust
Raw Normal View History

2020-11-20 03:53:50 +00:00
use anyhow::*;
use futures_core::future::BoxFuture;
use futures_util::FutureExt;
use log::LevelFilter;
use northstar::{Document, document::HeadingLevel, Request, Response, GEMINI_PORT};
#[tokio::main]
async fn main() -> Result<()> {
env_logger::builder()
.filter_module("northstar", LevelFilter::Debug)
.init();
northstar::Server::bind(("localhost", GEMINI_PORT))
.add_route("/", handle_base)
.add_route("/route", handle_short)
.add_route("/route/long", handle_long)
.serve()
.await
}
2020-11-20 18:22:34 +00:00
fn handle_base(req: Request) -> BoxFuture<'static, Result<Response>> {
let doc = generate_doc("base", &req);
2020-11-20 03:53:50 +00:00
async move {
Ok(Response::document(doc))
}.boxed()
}
2020-11-20 18:22:34 +00:00
fn handle_short(req: Request) -> BoxFuture<'static, Result<Response>> {
let doc = generate_doc("short", &req);
2020-11-20 03:53:50 +00:00
async move {
Ok(Response::document(doc))
}.boxed()
}
2020-11-20 18:22:34 +00:00
fn handle_long(req: Request) -> BoxFuture<'static, Result<Response>> {
let doc = generate_doc("long", &req);
2020-11-20 03:53:50 +00:00
async move {
Ok(Response::document(doc))
}.boxed()
}
2020-11-20 18:22:34 +00:00
fn generate_doc(route_name: &str, req: &Request) -> Document {
let trailing = req.trailing_segments().join("/");
2020-11-20 03:53:50 +00:00
let mut doc = Document::new();
doc.add_heading(HeadingLevel::H1, "Routing Demo")
.add_text(&format!("You're currently on the {} route", route_name))
2020-11-20 18:22:34 +00:00
.add_text(&format!("Trailing segments: /{}", trailing))
2020-11-20 03:53:50 +00:00
.add_blank_line()
.add_text("Here's some links to try:")
.add_link_without_label("/")
.add_link_without_label("/route")
.add_link_without_label("/route/long")
.add_link_without_label("/route/not_real")
.add_link_without_label("/rowte");
2020-11-20 03:53:50 +00:00
doc
}