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
相关推荐
恋喵大鲤鱼39 分钟前
Rust 中 package crate 和 module 的关系
rust
Rust研习社1 小时前
Rust 官方拟定 LLM 政策,防止 LLM 污染开源社区?
开发语言·后端·ai·rust·开源
techdashen1 小时前
Async Rust 近况补课:从 `async-trait` 到原生 async trait
网络·算法·rust
techdashen2 小时前
在 Async Rust 中实现请求合并(Request Coalescing)
开发语言·后端·rust
咸甜适中18 小时前
rust语言学习笔记Trait(八)Iterator(迭代器)
笔记·学习·rust
zoomdong1 天前
@utoo/pack: 基于 Turbopack 的下一代 Rust 构建工具
webpack·rust·开源
lolo大魔王1 天前
Go 语言 HTTP 协议与 RESTful API 实训全解(理论 + 实战 + 规范)
http·golang·restful
数据法师2 天前
MotrixNext:接棒经典 Motrix,用 Tauri 2+Rust 重构的下一代开源下载神器
重构·rust·开源
卡卡军2 天前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust