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 性能提升“最后一公里”:详解 Profiling 瓶颈定位与优化|得物技术
后端·rust
集成显卡9 小时前
Rust 实战五 | 配置 Tauri 应用图标及解决 exe 被识别为威胁的问题
后端·rust
集成显卡1 天前
Rust 实战四 | Traui2+Vue3+Rspack 开发桌面应用:通配符掩码计算器
后端·程序员·rust
维维酱2 天前
四、VGA 文本缓冲区基础
rust
寻月隐君2 天前
Rust 实战:从零构建一个多线程 Web 服务器
后端·rust·github
受之以蒙2 天前
Rust & WebAssembly 性能调优指南:从毫秒级加速到KB级瘦身
笔记·rust·webassembly
Vallelonga2 天前
关于 Rust 异步(无栈协程)的相关疑问
开发语言·后端·rust
q567315232 天前
Rust爬虫与代理池技术解析
开发语言·爬虫·python·rust
RustFS3 天前
如何用 Trae + RustFS MCP 实现自然语言对对象存储的操作?
rust·trae
浪费笔墨3 天前
基于rust的RGBA颜色混合
rust