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
相关推荐
雷中听风6 小时前
使用字节的源安装rust
开发语言·后端·rust
简单点好不好16 小时前
2025-简单点-从0开始学Rust-更新
rust
EniacCheng2 天前
【RUST】学习笔记-整型
笔记·学习·rust
Z.yping2 天前
qt语言家一键更新或发布多个模块且多个国家的语言
开发语言·qt·restful
小灰灰搞电子2 天前
Rust可以取代C++么?
开发语言·c++·rust
百锦再3 天前
京东云鼎入驻方案解读——通往协同的“高架桥”与“快速路”
android·java·python·rust·django·restful·京东云
异步思考者3 天前
Rust实战:一个内存消息队列的 Trait 驱动开发
rust
受之以蒙3 天前
智能目标检测:用 Rust + dora-rs + yolo 构建“机器之眼”
人工智能·笔记·rust
熬了夜的程序员3 天前
【Rust学习之路】第 0 章:理解 Rust 的核心哲学
开发语言·学习·rust
EniacCheng3 天前
【RUST】学习笔记-环境搭建
笔记·学习·rust