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
相关推荐
MageGojo14 小时前
R-Shell开源项目实战解析:用Rust打造命令行SSH工具,支持连接管理、远程执行、SFTP与MCP
运维·rust·开源项目·命令行工具·ssh客户端·mcp
techdashen15 小时前
Cargo 1.94 开发周期全解析
开发语言·后端·rust
fox_lht16 小时前
15.4.循环和迭代器的性能比较
开发语言·后端·学习·rust
guyoung17 小时前
BoxAgnts 工具系统(5)——WASM 工具开发:从 Hello World 到生产部署
rust·agent·ai编程
星栈18 小时前
写 Makepad Demo 不难,难的是把它写成项目
前端·rust
咸甜适中18 小时前
rust语言学习笔记Trait(十七)Send、Sync(线程间数据所有权)
笔记·学习·rust
javajenius19 小时前
Pixi:用 Rust 重写 Conda 体验的包管理工具
开发语言·其他·rust·conda
laowangpython19 小时前
tokio-rstracing:Rust 可观测性的标准答案
开发语言·后端·其他·rust
星栈独行19 小时前
写 Makepad Demo 不难,难的是把它写成项目
前端·程序人生·ui·rust
阿正的梦工坊1 天前
【Rust】12-借用检查器与非词法生命周期
开发语言·后端·rust