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
相关推荐
AIFQuant9 分钟前
量化交易系统:历史行情 API 批量拉取与回测数据清洗
开发语言·python·金融·restful·量化交易
qwepoih21 小时前
用 Rust 从零打造一个 CLI 脚手架工具
rust
咸甜适中3 小时前
rust语言学习笔记Trait(十)PartialOrd、Ord(大小比较)
笔记·学习·rust
codealy3 小时前
Rust 核心理论: 高并发与异步(四)
算法·rust
星栈4 小时前
订单状态机别写散:我在 Rust CRM 里把 6 个状态收进领域模型
后端·rust·全栈
恋喵大鲤鱼4 小时前
Rust 属性语法
rust·属性
月诸清酒7 小时前
AI 加剧了 Rust 替换前端基建的脚步:AI 时代,开发语言何去何从
开发语言·人工智能·rust
想你依然心痛7 小时前
HarmonyOS 6 悬浮导航 + 沉浸光感:打造鸿蒙智能体驱动的沉浸式AR导航助手
ar·restful·harmonyos·智能体
l1t1 天前
DeepSeek总结的将 Rust Delta Kernel 集成到 ClickHouse
数据库·clickhouse·rust
techdashen1 天前
在 Rust 异步接口的丛林中生存:从同步 I/O 到手写异步状态机
开发语言·后端·rust