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
相关推荐
十里平湖满秋霜5 小时前
RUST基础语法--数据类型
rust
Amos_Web9 小时前
Rspack 源码解析 (1) —— 架构总览:从 Node.js 到 Rust 的跨界之旅
前端·rust·node.js
Source.Liu9 小时前
【office2pdf】 项目规则(CLAUDE.md)
rust·office2pdf
望眼欲穿的程序猿11 小时前
MacOS自定义安装Rust
开发语言·macos·rust
Source.Liu12 小时前
【office2pdf】PPTX 字体解析与文本样式继承(PPTX_FONT_RESOLUTION.md)
rust·office2pdf
Rust研习社13 小时前
手把手带你写 Rust 文档
rust
迷藏49414 小时前
# 发散创新:用Rust构建高性能分布式账本节点——从零实现共识算法与链上数据存储
java·python·rust·共识算法·分布式账本
古城小栈14 小时前
Tonic:构建高性能 Rust gRPC 服务
开发语言·rust
Rust语言中文社区1 天前
【Rust日报】 Danube Messaging - 云原生消息平台
开发语言·后端·rust
2501_921649491 天前
RESTful 金融数据 API 文档:设计原则与最佳实践
开发语言·后端·python·金融·restful