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 分钟前
【后端】【Java】一文深入理解 Spring Boot RESTful 风格接口开发
java·spring boot·restful
云雾J视界4 小时前
告别手动寄存器编程:STM32-RS 生态如何重构嵌入式开发效率
rust·svd·嵌入式开发·寄存器·工具链·可编译·社区驱动
Source.Liu20 小时前
【time-rs】月份枚举实现
rust·time
福大大架构师每日一题1 天前
2025年12月TIOBE编程语言排行榜,Go语言排名第15,Rust语言排名17。编程语言 R 重返前十。
开发语言·后端·rust
苏 凉1 天前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
ULTRA??1 天前
字符串处理小写字母转换大写字母
c++·python·rust
中文很快乐2 天前
从零到一:用 SpringBoot 打造 RESTful API 实战指南
java·spring boot·后端·restful
ZC·Shou2 天前
Rust 之二 各组件工具的源码、构建、配置、使用(二)
开发语言·ide·rust·工具·命令·clippy·rustfmt
ULTRA??2 天前
Rust的移动语义
c++·算法·rust
熬了夜的程序员2 天前
【Rust学习之路】序
开发语言·后端·学习·rust