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+Slint 实现FTP客户端调试助手源码分享
开发语言·后端·rust
Flynt10 小时前
Cloudflare 用 Rust 重写了 TypeScript:我拿同一批代码跑了跑,报错一模一样,退出码不一样
rust·typescript·前端工程化
miofly18 小时前
GitHub 今日推荐|pandacode:本地桌面统一管理多个AI编码代理
rust·开源·github
怪我冷i18 小时前
Rust 核心语法与内存安全机制
开发语言·安全·rust
程工造Agent2 天前
从 0 到 1 学 Codex 源码:顺着 main 读懂 Rust 闭包与 async move
rust·ai编程
shimly1234562 天前
(done) RUST 指针详解
rust
geovindu2 天前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
遇码2 天前
Rust 桌面应用自托管自动更新:latest.json 清单 + minisign 签名校验的完整做法
人工智能·ai·rust·大模型·agent
geovindu2 天前
rust: Template Method Pattern(续)
开发语言·后端·设计模式·rust·行为模式·板方法模式
专注仿真2 天前
ThinkPHP6 API接口开发实例:从零搭建RESTful风格接口
后端·php·restful