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
相关推荐
铅笔侠_小龙虾21 分钟前
Rust 学习(4)-函数与注释
开发语言·学习·rust
前端H2 小时前
Biome & Rolldown:Rust 工具链接管前端基建
开发语言·前端·rust
独孤留白3 小时前
从C到Rust:struct Cell / RefCell 线程内局部可变性
rust
Kapaseker3 小时前
Rust 是如何处理异常的
rust·kotlin
铅笔侠_小龙虾5 小时前
Rust 学习(8)-切片类型
学习·rust·c#
程序员爱钓鱼8 小时前
Rust 函数与返回值详解:参数、表达式与返回类型
后端·rust
花褪残红青杏小14 小时前
Rust图像处理第17节-Julia 朱利亚分形:拖动常数 c 看图实时变化
rust·webassembly·图形学
An_s19 小时前
rust开发wasm与浏览器(js)交互
javascript·rust·wasm
Mr -老鬼21 小时前
Zed WASM扩展开发全套踩坑记录(WASI适配、LSP插件开发避坑指南)
rust·wasm·lsp·zed·ai ide·语言服务器
糯米导航1 天前
Rust + ONNX Runtime 构建生产级 AI 推理服务:从零到压测
开发语言·人工智能·rust