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
相关推荐
栈与堆13 小时前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
小北方城市网14 小时前
微服务注册中心与配置中心实战(Nacos 版):实现服务治理与配置统一
人工智能·后端·安全·职场和发展·wpf·restful
AIFQuant15 小时前
2026 全球外汇免费实时行情汇率数据 API 接口大全
开发语言·python·websocket·金融·restful
盛者无名21 小时前
Rust的所有权(Owenership)
开发语言·rust
BlockChain88821 小时前
MPC 钱包实战(三):Rust MPC Node + Java 调度层 + ETH 实际转账(可运行)
java·开发语言·rust
分布式存储与RustFS1 天前
RustFS在AI场景下的实测:从GPU到存储的完整加速方案
开发语言·人工智能·rust·对象存储·企业存储·rustfs·minio国产化替代
柠檬丶抒情2 天前
Rust no_std 裸机移植:9 条避坑与实战手册
开发语言·mongodb·rust
FAFU_kyp2 天前
Rust 流程控制学习教程
学习·算法·rust
FAFU_kyp2 天前
Rust 模式匹配:match 与 if let 详解
开发语言·后端·rust
爱上妖精的尾巴2 天前
7-10 WPS JS宏 对象使用实例7--拆分单表到多工作簿下的多表
javascript·restful·wps·jsa