pub async fn bind(
tx: Sender<(ReloadType, Vec<PathBuf>)>,
config: Config,
) -> Result<(String, TcpListener, Router), String>Expand description
Bind to config.ip:config.port and build the router.
Returns the url, the bound listener and the router.
Use 0 as config.port to let the OS pick a free port (the real one is in the url).
ยงExamples
use std::net::IpAddr;
use axum::{Router, routing::get};
use tempfile::tempdir;
use tokio::sync::broadcast;
use webadev::{Config, bind, serve};
#[tokio::main]
async fn main() {
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("index.html"), "<h1>hi</h1>").unwrap();
let (tx, _rx) = broadcast::channel(100);
let config = Config {
dir: dir.path().to_path_buf(),
ip: IpAddr::from([127, 0, 0, 1]),
port: 0,
headers: vec![],
index: "index.html".into(),
base: String::new(),
};
let (url, listener, router) = bind(tx, config).await.unwrap();
// Here you can tweak the axum router
let router = router.route("/health", get(|| async { "ok" }));
let url = url.clone();
tokio::spawn(async move { let _ = serve(listener, router).await; });
let body = reqwest::get(format!("{url}/health"))
.await
.unwrap()
.text()
.await
.unwrap();
assert_eq!(body, "ok");
}