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
相关推荐
MC皮蛋侠客4 小时前
Tauri 2.x 系列(五):调用系统 API——官方插件、Rust crate 与原生能力
开发语言·后端·rust
磐链科技9 小时前
钱包开发中的跨平台架构:Flutter与Rust构建高性能移动端钱包
flutter·架构·rust
MC皮蛋侠客11 小时前
Tauri 2.x 系列(四):窗口、菜单、托盘与应用生命周期——做出真正的桌面体验
rust·tauri
MC皮蛋侠客11 小时前
Tauri 2.x 系列(一):架构全景与最小闭环——从 WebView 到 EMS 后台
架构·rust·tauri
今天AI了吗14 小时前
从“金鱼脑”到“大象记忆”:AI Agent 短期记忆与长期记忆的存储与检索全解
数据库·人工智能·python·sql·rust
MC皮蛋侠客14 小时前
Tauri 2.x 系列(二):项目结构与前端框架——Vue、React 如何成为桌面前台
rust·tauri
++==1 天前
RESTful详解:核心思想、框架、与HTTP的区别,API的设计风格
后端·http·restful
@atweiwei1 天前
用 Rust 构建 Agent 应用的高性能框架:langchainrust 架构全景
人工智能·架构·rust·langchain·llm·agent·ai编程
Source.Liu2 天前
【Dioxus】Dioxus CLI (dx) 命令笔记
笔记·rust·dioxus