Rust:用 Warp 库实现 Restful API 的简单示例

直接上代码:

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
相关推荐
撸码猿3 小时前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
wflynn3 小时前
GitHub 今日推荐|xcl:在 Windows PC 上直接运行 Xbox Series X|S 游戏
rust·开源·github·d3d12·gdk·rdna2
geovindu21 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
喵个咪1 天前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
喵个咪1 天前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
geovindu2 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
关键词安全2 天前
PHP / Node.js / Go / Rust 全部中招(CVE-2026-109618、109619、111497、111943)完整排查与修复清单
golang·rust·node.js
xjz18423 天前
Rust 的`+=`、`-=`、`*=`、`/=` —— 让变量更新更简洁
rust
xjz18424 天前
Rust 用 `&&`、`||`、`!` 把条件组合起来
rust
不积跬步无以至千里mmbb264 天前
Rust三大核心:Trait Crate Mod详解
linux·rust