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
相关推荐
鲁正杰7 小时前
【运维部署】现代化内网穿透与文件共享方案 (Rust)
运维·开发语言·rust
superman超哥12 小时前
Rust `‘static` 生命周期:从字面意义到深层语义
开发语言·后端·rust·生命周期·编程语言·rust static·深层语义
半夏知半秋13 小时前
rust学习-Option与Result
开发语言·笔记·后端·学习·rust
superman超哥15 小时前
Rust 结构体中的生命周期参数:所有权设计的核心抉择
开发语言·后端·rust·rust结构体·rust生命周期·所有权设计
lusasky15 小时前
在Windows上编译、安装Rust
开发语言·windows·rust
半夏知半秋15 小时前
rust学习-探讨为什么需要标注生命周期
开发语言·笔记·学习·算法·rust
superman超哥15 小时前
Rust 生命周期边界:约束系统的精确表达
开发语言·后端·rust·rust生命周期边界·约束系统
superman超哥15 小时前
Rust 生命周期省略规则:编译器的智能推导机制
开发语言·后端·rust·编译器·rust生命周期·省略规则·智能推导
xuejianxinokok16 小时前
rust trait 相比于传统的 oop 有哪些优点?
后端·rust