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
相关推荐
无名之逆10 小时前
你可能不需要WebSocket-服务器发送事件的简单力量
java·开发语言·前端·后端·计算机·rust·编程
Source.Liu11 小时前
【egui】界面的坐标系统:f32 一统江湖
rust·egui
班公湖里洗过脚17 小时前
Rust解析mp3文件及工作目录下多个项目维护示例
rust
sunny_1 天前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
用户0235087373121 天前
第02篇:5分钟上手 blockcell —— 从安装到第一次对话
rust
badmonster01 天前
我写了一个超轻量MCP,让编码Agent真正理解你的代码——Token消耗减少70%,1分钟接入
rust·ai编程
RoyLin2 天前
10美元硬件中可运行的隐私 LLM 推理引擎
人工智能·rust·agent
Source.Liu2 天前
【egui】[特殊字符] 窗口配置小抄:eframe::NativeOptions
rust·egui
Hello.Reader2 天前
Tauri 项目结构前端壳 + Rust 内核,怎么协作、怎么构建、怎么扩展
开发语言·前端·rust
Source.Liu2 天前
【egui】[特殊字符]简单、快速、跨平台的 Rust GUI 库
rust·egui