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
相关推荐
weixin_502539852 小时前
rust学习笔记21-闭包
笔记·学习·rust
橘右溪2 小时前
Windows 下 Rust 快速安装指南
rust
fundroid2 小时前
Rust 为什么不适合开发 GUI
开发语言·后端·rust
w4ngzhen10 小时前
理解Rust引用及其生命周期标识(下)
rust
残轩13 小时前
是时候考虑用uv管理你的python项目及依赖了
python·rust
Source.Liu13 小时前
【学Rust写CAD】18 定点数2D仿射变换矩阵结构体(MatrixFixedPoint结构别名)
矩阵·rust·cad
橘右溪15 小时前
前端快速系统学习Rust的路径
rust
江南月17 小时前
Rust+WebAssembly 高性能图像处理引擎开发实战
前端·rust
Tee xm17 小时前
清晰易懂的Rust安装与配置教程
linux·windows·macos·rust
aimmon19 小时前
Rust从入门到精通之精通篇:26.性能优化技术
开发语言·性能优化·rust