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
相关推荐
SomeB1oody3 小时前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程
Embedded-Xin4 小时前
Rust学习——Cargo工具
linux·学习·架构·rust·嵌入式
龙仔7254 小时前
RustDesk 完整笔记
运维·笔记·rust·远程工具·rustdesk
An_s5 小时前
rust(pdfium)底层开发实现wasm包给vue3调用
开发语言·rust·wasm
对象存储与RustFS8 小时前
为什么越来越多的企业选择RustFS作为对象存储?
后端·rust·开源
KryptonWright1 天前
让 AI Agent 只能提议、不能擅自执行:Rust 中 prepare-confirm-execute 权限模型的实现
rust
起司喵喵1 天前
推荐一款基于 Python 和 Rust 开发的跨平台 GUI 自动化库!
python·rust·自动化
花褪残红青杏小2 天前
Rust图像处理第24节- 噪声模型 + 中心极限定理:椒盐噪声 + CLT 可视化
rust·webassembly·图形学
爱吃牛肉的大老虎2 天前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
TunerT_TQ2 天前
Valhalla 静态工程审阅 #008|RisingWave 源码证据驱动评测【大厂开源基础设施特辑】
rust·开源·github·实时数据处理·流式数据库·apacheflink·streamingsql