DEV Community

NotFound404
NotFound404

Posted on

Develope Rust Web the Express JS way

Get Started

Add the dependency with a single command:

cargo add aex
cargo add tokio --features full
Enter fullscreen mode Exit fullscreen mode

Spin up an HTTP service in 30 seconds

use aex::http::router::Router as HttpRouter;
use aex::server::Server;
use aex::{_sync, http};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let addr: SocketAddr = "0.0.0.0:8080".parse()?;
    let mut router = HttpRouter::default();

    router.get("/", _sync!(|_| "OK"));

    Server::default()
        .push(http!(router))
        .start(addr)
        .await?;
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

For async handlers, just wrap them with _async!

use aex::http::router::Router as HttpRouter;
use aex::server::Server;
use aex::{_async, http};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let addr: SocketAddr = "0.0.0.0:8080".parse()?;
    let mut router = HttpRouter::default();
    // Async closure: `_async!` supports await internally, and likewise needs no annotation
    router.get("/", _async!(|ctx| {
        let html = fetch_home_page().await; // any async logic
        ctx.html(&html);
        true
    }));

    Server::default()
        .push(http!(router))
        .start(addr)
        .await?;
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)