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
相关推荐
self-motivation13 小时前
cuda编程 --------- warp 级别规约指令 __shfl_xor_sync
cuda·hpc·warp·shfl_xor_sync·dot product
爱学习的小可爱卢18 小时前
编程语言30年:从Java到Rust的进化史
java·开发语言·rust
捧 花18 小时前
Go Web 开发流程
开发语言·后端·golang·restful·web·分层设计
archko20 小时前
用rust写了一个桌面app,就不再想用kmp了
开发语言·后端·rust
星释21 小时前
Rust 练习册 109:深入探索列表关系判断
开发语言·后端·rust
星释21 小时前
Rust 练习册 110:探索倍数之和的数学之美
开发语言·后端·rust
码农阿豪21 小时前
用 Rust 构建 Git 提交历史可视化工具
git·elasticsearch·rust
塵觴葉21 小时前
基于Rust/Qt的五笔编码查询工具
qt·rust·新世纪五笔
问道飞鱼21 小时前
【开发语言】Rust语言介绍
开发语言·后端·rust
秋邱2 天前
AR 技术团队搭建与规模化接单:从个人到团队的营收跃迁
前端·人工智能·后端·python·html·restful