直接上代碼:
1、源文件 Cargo.toml
[package]
name = "xcalc"
version = "0.1.0"
edition = "2021"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
warp = "0.3"
tokio = { version = "1", features = ["full"] }
2、源文件:main.rs
use warp::{Filter, reply, Rejection}; // 引入 Rejection
#[tokio::main]
async fn main() { // 創建一個簡單的 GET /hello 路由,返回 "hello" let hello = warp::path!("hello") .map(|| "hello") .and_then(|msg| async move { Ok::<_, Rejection>(reply::html(msg)) }); // 顯式指定 Result 的 Err 類型為 Rejection // 運行 Warp 服務器并監聽 8080 端口 warp::serve(hello) .run(([127, 0, 0, 1], 8080)) .await;
}
3、運行測試
首先編譯并運行上述程序,然后再打開一個新的命令行窗口,輸入下面的測試命令:
curl http://localhost:8080/hello
可以看到顯示結果為:
hello