Expand description
Support for the axum web server framework in wasi-http components, via
wstd.
This crate is a pretty thin wrapper on wstd that allows users to
use the axum crate on top of wstd’s http support. This means that
axum services can run anywhere the wasi-http proxy world is supported,
e.g. in wasmtime serve.
Users of this crate should depend on axum with default-features = false, and opt in to any features that they require (e.g. form, json,
matched-path, original-uri, query, tower-log, tracing). The axum crate
features that require hyper or tokio are NOT supported (e.g. http1,
http2, ws), because unlike in native applications, wasi-http components
have an http implementation provided as imported interfaces (i.e.
implemented the Wasm host), and do not use raw sockets inside of this
program.
§Examples
The simplest use is via the wstd_axum::http_server proc macro.
This macro can be applied to a sync or async fn main which returns
an impl of the tower_service::Service trait, typically an
axum::Router:
//! Run with
//!
//! ```sh
//! cargo build -p wstd-axum --examples --target wasm32-wasip2
//! wasmtime serve -Scli target/wasm32-wasip2/debug/examples/hello-world.wasm
//! ```
use axum::{Router, response::Html, routing::get};
#[wstd_axum::http_server]
fn main() -> Router {
// build our application with a route
Router::new().route("/", get(handler))
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}If users desire, they can instead use a wstd::http_server entry point
and then use wstd_axum::serve directly. The following is equivelant
to the above example:
//! Run with
//!
//! ```sh
//! cargo build -p wstd-axum --examples --target wasm32-wasip2
//! wasmtime serve -Scli target/wasm32-wasip2/debug/examples/hello-world-nomacro.wasm
//! ```
use axum::{Router, response::Html, routing::get};
use wstd::http::{Body, Error, Request, Response};
#[wstd::http_server]
async fn main(request: Request<Body>) -> Result<Response<Body>, Error> {
let service = Router::new().route("/", get(handler));
wstd_axum::serve(request, service).await
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}