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
相关推荐
程序员爱钓鱼8 小时前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
段一凡-华北理工大学20 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
大卫小东(Sheldon)1 天前
小鹤音形词典:一个用 Rust 写的离线编码查询桌面工具
ai·rust
就业发动机1 天前
我用 Tauri 做了一个约 1.5 MB 的开源屏幕标注工具:MarkerOn
vue.js·rust
2601_954526751 天前
【硬核架构】打破 IT 与 OT 的数据孤岛!基于 Rust 异步协程的工业 IoT 网关重构,兼谈顶级自动化智能仪表厂家选型指南
物联网·架构·rust
white_ant1 天前
17- 文本统计/处理工具使用指南
rust·个人开发·tauri
独孤留白1 天前
Rust 类型转换全景指南 —— 从引用转换到序列化
rust
独孤留白1 天前
从C到Rust:Trait TryFrom TryInto 可能失败的类型转换
rust
雨师@1 天前
python通过rust编写组件扩展自己的能力
python·rust
程序员爱钓鱼1 天前
Rust 切片 Slice 详解:安全访问连续数据
前端·后端·rust