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
相关推荐
techdashen4 分钟前
Rust 正式成立 Types Team:类型系统终于有了专属团队
开发语言·后端·rust
bilI LESS2 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
Rust研习社2 小时前
深入理解 Rust 裸指针:内存操作的双刃剑
开发语言·后端·rust
浪客川13 小时前
【百例RUST - 010】字符串
开发语言·后端·rust
木心术120 小时前
RESTful API设计最佳实践:构建可扩展的后端服务
后端·restful
好家伙VCC20 小时前
# 发散创新:用 Rust实现高性能物理引擎的底层架构设计与实战在游戏开发、虚拟仿真和机器人控
java·开发语言·python·rust·机器人
代码羊羊21 小时前
Rust所有权与引用:核心要点速记
rust
浪客川1 天前
【百例RUST - 009】容器 Vector
开发语言·rpc·rust
Rust研习社1 天前
Rust Default 特征详解:轻松实现类型默认值
开发语言·后端·rust
Rust研习社1 天前
Rust Copy 特征详解|新手必看!再也不与 Clone 混淆
后端·rust·编程语言