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
相关推荐
doiito(Do It Together)42 分钟前
【安全,架构】RustyVault 项目深度分析报告以及和HashiCorp Vault的差异
微服务·架构·rust
问窗1 小时前
Rust实现Windows本地搜索工具
windows·搜索引擎·rust
程序员爱钓鱼2 小时前
Rust 变量与不可变性:为什么默认不能修改变量?
前端·后端·rust
第一程序员13 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
IT笔记15 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
取地址符19 小时前
Rust学习笔记(基于Rustlings)(2):数据结构与集合
笔记·学习·rust
取地址符20 小时前
Rust语法学习 (基于Rustlings)(1):基础语法
经验分享·笔记·学习·rust
记忆着1 天前
Rust基础入门二
rust
doiito1 天前
【安全,架构】RustyVault 项目深度分析报告以及和HashiCorp Vault的差异
后端·安全·rust