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
相关推荐
姜 萌@cnblogs31 分钟前
开源我的一款自用AI阅读器,引流Web前端、Rust、Tauri、AI应用开发
rust·web·tauri·svelte
明月看潮生11 小时前
青少年编程与数学 02-019 Rust 编程基础 05课题、复合数据类型
开发语言·青少年编程·rust·编程与数学
Bruce_Liuxiaowei14 小时前
Day 5:Warp高级定制与自动化
运维·warp
Uncomfortableskiy16 小时前
Rust 官方文档:人话版翻译指南
开发语言·rust
大卫小东(Sheldon)17 小时前
GIM: 调用AI自动生成git提交消息的工具
git·rust
zz0723201 天前
第二十一周:项目开发中遇到的相关问题(二)
java·spring·restful
大G哥1 天前
Rust 之 trait 与泛型的奥秘
java·开发语言·jvm·数据结构·rust
Source.Liu1 天前
【typenum】 1 说明文件(README.md)
rust
蜗牛沐雨2 天前
Rust 中的 Pin 和 Unpin:内存安全与异步编程的守护者
服务器·开发语言·rust
hrrrrb2 天前
【Rust】枚举和模式匹配
开发语言·rust