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
相关推荐
2601_966494721 天前
C语言是什么
c语言·rust·linux内核·内存管理·系统编程
RobinDevNotes1 天前
黄仁勋复职之外,AI这周还有6件大事
人工智能·rust·人工智能开发工具
吴佳浩2 天前
我和 rust-anything:AI 时代,重写代码不再靠“信心“,而靠“证据“
人工智能·rust·go
Java码农也是农2 天前
Rust、Java、Python、C++ 有什么区别?从 CPU 执行到内存管理
java·python·rust
可夫小子3 天前
AI 写了 200 万行 Rust 克隆闭源二进制分析软件,软件保护的旧防线还稳吗
rust
johnsong3 天前
AI前沿日报 · 2026-11-27:超人优化器、推理账单与 Rust 重写
rust·openai·anthropic·黎曼猜想·数学优化·ai前沿日报·gpt-6.2
Kapaseker4 天前
离开 Swift,转向 Rust
rust
钱栈up4 天前
GitHub 热榜实测|worktrunk 环境部署实录
rust·开源·github
喵个咪5 天前
RushWind Shop — 一笔订单的穿越:电商买路径上的每一道闸门
后端·微服务·rust
Kapaseker5 天前
5分钟学会 Rust 常见集合
rust