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
相关推荐
AOwhisky16 小时前
下一代容器来了?Docker 宣布原生支持 WebAssembly
java·运维·docker·容器·rust·wasm
铅笔侠_小龙虾1 天前
Rust 学习(6)-所有权规则、移动语义、Clone 与 Copy
python·学习·rust
程序员爱钓鱼1 天前
Rust 控制流 if 详解:条件判断与 if 表达式
前端·后端·rust
花褪残红青杏小2 天前
Rust图像处理第19节-RGB 色彩矩阵变换:矩阵 × 向量 = 像素变换
rust·webassembly·图形学
white_ant2 天前
15-ASCII 转换工具使用指南
rust·tauri·watools
碎碎念_4922 天前
前后端分离项目开发规范
nginx·vue·springboot·restful
铅笔侠_小龙虾2 天前
Rust 学习(2)-变量、常量与 shadowing
学习·算法·rust
独孤留白2 天前
从C到Rust:Mutex / RwLock / Atomic 跨线程局部可变性
rust
程序员爱钓鱼2 天前
Rust 注释与文档注释详解:从代码说明到 cargo doc
后端·rust
花褪残红青杏小3 天前
Rust图像处理第18节-分形画布缩放 + 拖拽交互:图像缩放 + f32 性能优化
rust·webassembly·图形学