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
相关推荐
零点一顿微胖8 小时前
[Agent]实现获取系统基本信息接口 Rust版
开发语言·rust
小宇子2B9 小时前
Copy 明明比 Clone 便宜,为什么 Rust 偏偏要求你「先实现 Clone」?
rust
小宇子2B10 小时前
一个 Vec 在内存里到底长什么样:从真实地址看 move 为什么不要钱
rust
特立独行的猫a14 小时前
鸿蒙 PC 移植记:将微软的 `edit` 轻量级终端编辑器带到 OpenHarmony
microsoft·rust·编辑器·harmonyos·鸿蒙pc·edit
@小匠14 小时前
WebDAV 同步踩坑实录:从 405 到数据恢复不生效的完整排查
rust
爱学习的鱼佬16 小时前
告别内网模型接入烦恼!ModelStandardization:让 Open WebUI等工具无缝对接私有大模型
rust·开源·大模型·openai·openwebui·model api代理·内网部署
Rust研习社1 天前
90% 的 Rust 新手都不知道的 3 个实用开发技巧
后端·rust·编程语言
析数塔2 天前
编译两分钟,修改五秒钟:Zig构建系统重构解决的老问题
程序员·rust
Kapaseker2 天前
Rust 是如何干掉空指针的
rust·kotlin
特立独行的猫a2 天前
OHOS (OpenHarmony) 鸿蒙的Rust 交叉编译环境搭建指南
华为·rust·harmonyos·鸿蒙pc