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
相关推荐
golang学习记13 小时前
rust开发,选VS Code还是RustRover?
开发语言·后端·rust
滕州市燕猫虎计算机科技工作室个体工商户13 小时前
《Rust程序设计》学习笔记二
rust·学习笔记
滕州市燕猫虎计算机科技工作室个体工商户14 小时前
《Rust程序设计》学习笔记三
rust·学习笔记·rust程序设计
geovindu15 小时前
rust: Facade Pattern
开发语言·后端·设计模式·rust·外观模式
福大大架构师每日一题15 小时前
Rust 1.99.0发布:C 可变参数、裸函数、Cargo 配置、Rustdoc 性能与大量兼容性调整全解析
c语言·开发语言·rust
DongQiShanRen16 小时前
裁决台账双向互校(下):台账哈希链、三向对账与最小落地
人工智能·深度学习·算法·目标跟踪·自然语言处理·rust·哈希算法
行者-全栈开发16 小时前
华为云码道 CodeArts 实测:让 AI 用 Rust 写一个 Git 仓库健康度体检台「仓衡」
git·rust·tauri·桌面应用·ai 编程·华为云码道·codearts 代码智能体
miofly16 小时前
GitHub 今日推荐|lightcraft:纯 Rust 重写的 RAW 照片开发工具
rust·开源·github
ドロロ80619 小时前
openAPI与Restful API的区别
后端·restful
geovindu1 天前
rust: Abstract Factory pattern
开发语言·后端·设计模式·rust·抽象工厂模式