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
相关推荐
杨艺韬9 小时前
Rust编译器原理-第11章 闭包:匿名函数的编译器实现
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第15章 MIR 优化:编译器的中间表示与优化管线
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第6章 单态化:泛型的编译期展开
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第14章 宏系统:编译期的元编程引擎
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第16章 LLVM 代码生成:从 MIR 到机器码
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第5章 内存布局:编译器如何排列数据
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第3章 借用检查器:编译器如何证明内存安全
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第9章 async/await:状态机的编译器变换
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第8章 Trait Object 与虚表:运行时多态的内存布局
rust·编译器
杨艺韬9 小时前
Rust编译器原理-第13章 FFI:与 C 世界的桥梁
rust·编译器