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
相关推荐
辞山1 小时前
Coordinate SDK 技术解析
rust
想你依然心痛1 小时前
HarmonyOS 6(API 23)实战:打造“空间交互式AR健身私教“——基于Face AR疲劳监测 + Body AR姿态识别的沉浸光感运动系统
ar·restful·harmonyos·悬浮导航·沉浸光感
qcx232 小时前
【AI Agent通识九课】 04 · AI 的双车道 — 安全怎么保
人工智能·安全·agent·ai agent·warp
skilllite作者19 小时前
SkillLite 原生系统级沙箱功能代码导览
人工智能·chrome·后端·架构·rust
时空系1 天前
第13篇:综合实战——制作我的小游戏 Rust中文编程
开发语言·后端·rust
沿途的风景X1 天前
我用 Rust 写了个数据文件预览工具,167MB Parquet 35ms 出结果
rust·数据分析·命令行
Rust研习社1 天前
Weak 弱引用:如何用 Weak 打破 Rc 与 Arc 的循环引用
开发语言·后端·rust
qcx231 天前
【AI Agent通识九课】05 · AI 的红绿灯 — 长任务怎么管
人工智能·ai·agent·warp
DogDaoDao1 天前
【GitHub】Warp 终端深度解析:Rust + GPU 加速的 AI 原生终端开源架构
人工智能·程序员·rust·开源·github·ai编程·warp