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
相关推荐
爆米花byh4 小时前
在RockyLinux9环境下安装Rust1.100.0环境
linux·rust
hai3152475434 小时前
阶乘分层关系模型存储文本与表格
数据结构·算法·rust·排序算法·线性回归
Shota Kishi7 小时前
Solana Stream SDK 的 UDP Shred 接收:data-only 与 recover 两种模式的取舍与实测
rust·区块链·solana
tomatohug7 小时前
Tauri v2 实战:做一个贴在任何输入框上的提示词优化助手
rust
Zenova EdgeOS10 小时前
Rust 数据库实战:工业边缘场景下的 sqlx
数据库·oracle·rust·边缘计算·工业网关
用户46043852250861 天前
关于paimon- rust的学习 --- Table(一)
大数据·rust
Kapaseker1 天前
快 18 倍?Laravel Rust 才是 Laravel 的未来
rust
Edgarye1 天前
Rust + Vue 3 前后端开发框架 RyFrame:从参数更新到操作审计
rust
loulanyue_1 天前
AI智能体24小时复刻Photoshop:什么该交给Agent、什么必须留给人——读Brandon Thomas演讲实录
人工智能·ui·rust·ai编程·photoshop
wasabihu2 天前
为什么别给 AI 浏览器 MCP 开全盘文件上传:原生 CDP 零拷贝与 4 道 Fail-Closed 防线
rust