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
相关推荐
alwaysrun18 小时前
Rust 如何实现许可证管理系统
rust
编码浪子18 小时前
《安全 Rust 的边界在哪?》— 中文解读
开发语言·安全·rust
不知名的老吴1 天前
聊一聊年轻的编程语言Golang与Rust
开发语言·golang·rust
开开心心就好1 天前
支持批量处理的视频分割工具推荐
安全·智能手机·rust·pdf·电脑·1024程序员节·lavarel
浪客川1 天前
UniFFI 跨平台开发Rust 与 Android (Kotlin) 集成
android·rust·kotlin
芝士就是力量啊 ೄ೨1 天前
如何配置Rust、Git,并从Github上拉下一个项目
git·rust·github
eqwaak01 天前
4 月技术快讯|Rust 1.90 正式发布,系统级开发再进化
开发语言·后端·rust
techdashen1 天前
Cloudflare 如何把一个大型代理拆成三个小服务来提升可靠性
开发语言·rust