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
相关推荐
沉淀粉条形变量38 分钟前
rust 单例模式
开发语言·单例模式·rust
skilllite作者2 小时前
SkillLite 多入口架构实战:CLI / Python SDK / MCP / Desktop / Swarm 一页理清
开发语言·人工智能·python·安全·架构·rust·agentskills
Rust研习社2 小时前
深入理解 Rust 闭包:从基础语法到实战应用
rust
Rust研习社2 小时前
Rust 时间处理神器:chrono 从入门到实战
rust
Rust研习社3 小时前
Rust 异步 ORM 新选择:Toasty 初探
rust
星辰徐哥4 小时前
异步定时任务系统的设计与Rust实战集成
开发语言·后端·rust
swear014 小时前
【VSCODE 插件 rust-analyzer 使用】打开文件夹
ide·vscode·rust
laomocoder5 小时前
AI网关设计
人工智能·rust·系统架构
zandy10115 小时前
业界首发|衡石科技HENGSHI CLI重磅登场,以Rust架构开启Agentic BI自动驾驶时代
科技·架构·rust·agentic bi
王家视频教程图书馆6 小时前
rust 写gui 程序 最流行的是哪个
开发语言·后端·rust