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
相关推荐
@大迁世界6 小时前
相信我兄弟:Cloudflare Rust 的 .unwrap() 方法在 330 多个数据中心引发了恐慌
开发语言·后端·rust
2***B4497 小时前
Rust在系统编程中的内存安全
开发语言·后端·rust
U***e637 小时前
Rust错误处理最佳实践
开发语言·后端·rust
疏狂难除11 小时前
随便玩玩lldb (二)
开发语言·后端·rust
Rust语言中文社区13 小时前
【Rust日报】 丰田“先锋”选择了 Rust
开发语言·后端·rust
邹小邹-AI13 小时前
Rust + 前端:下一个十年的“王炸组合”
开发语言·前端·rust
本妖精不是妖精16 小时前
基于 Rokid Max 与 JSAR 构建空间锚定型 AR 信息面板
后端·ar·restful
芳草萋萋鹦鹉洲哦16 小时前
【tauri+rust】App会加载白屏,有时显示在左上角显示一小块,如何优化
开发语言·后端·rust
zengyuhan50316 小时前
Windows BLE 开发指南(Rust windows-rs)
前端·rust