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
相关推荐
星释14 小时前
Rust 练习册 120:探索向量与斐波那契数列
开发语言·后端·rust
gregmankiw14 小时前
Rust错误处理
rust
勇敢牛牛_14 小时前
【aiway】一个Rust实现的API网关
rust·api网关
朝阳58115 小时前
Rust 并行压缩如何改变我的工作流程
后端·rust
muyouking1116 小时前
Zig 模块系统详解:从文件到命名空间,与 Rust 的模块哲学对比
开发语言·后端·rust
muyouking1117 小时前
Zig vs Rust:常用类型声明方式对比与核心理念解析
rust
爱上妖精的尾巴17 小时前
5-39 WPS JS宏 综合实例应用-4(多条件筛选记录并排序)
java·后端·restful·wps·js宏·jsa
s91236010118 小时前
【rust】生成带白边的标准二维码
开发语言·后端·rust
爱上妖精的尾巴20 小时前
5-36 WPS JS宏综合实例应用-1(多工作表数据合并)
javascript·restful·wps
测试人社区—小叶子21 小时前
Rust会取代C++吗?系统编程语言的新较量
运维·开发语言·网络·c++·人工智能·测试工具·rust