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
相关推荐
Hello.Reader44 分钟前
深入理解 Rust 的 `Rc<T>`:实现多所有权的智能指针
开发语言·后端·rust
yoona10201 小时前
Rust编程语言入门教程(八)所有权 Stack vs Heap
开发语言·后端·rust·区块链·学习方法
guyoung2 小时前
DeepSeek轻量级本地化部署工具——AIMatrices DeepSeek
rust·llm·deepseek
JD技术委员会7 小时前
Rust 语法噪音这么多,是否适合复杂项目?
开发语言·人工智能·rust
Hello.Reader7 小时前
Rust 中的 `Drop` 特性:自动化资源清理的魔法
开发语言·rust·自动化
Vitalia7 小时前
从零开始学 Rust:基本概念——变量、数据类型、函数、控制流
开发语言·后端·rust
cheungxiongwei.com7 小时前
Rust 驱动的 Python 工具革命:Ruff 和 uv 与传统工具的对比分
python·rust·uv
wzhao1017 小时前
elf_loader:一个使用Rust编写的ELF加载器
linux·rust·gnu
泡泡Java9 小时前
使用WebStorm开发Vue3项目
ide·rust·webstorm
独好紫罗兰2 天前
通过例子学 rust 个人精简版 5-all
rust