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
相关推荐
AIFQuant21 小时前
如何快速接入贵金属期货实时行情 API:python 实战分享
开发语言·python·金融·数据分析·restful
FAFU_kyp1 天前
Rust 泛型(Generics)学习教程
开发语言·学习·rust
REDcker1 天前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
木木木一2 天前
Rust学习记录--C12 实例:写一个命令行程序
学习·算法·rust
柠檬丶抒情2 天前
Rust深度学习框架Burn 0.20是否能超过python?
python·深度学习·rust·vllm
Vallelonga2 天前
浅谈 Rust bindgen 工具
开发语言·rust
木木木一2 天前
Rust学习记录--C13 Part1 闭包和迭代器
开发语言·学习·rust
木木木一2 天前
Rust学习记录--C13 Part2 闭包和迭代器
开发语言·学习·rust
Vallelonga2 天前
Rust 中 extern “C“ 关键字
c语言·开发语言·rust
小北方城市网3 天前
SpringBoot 安全认证实战(Spring Security + JWT):打造无状态安全接口体系
数据库·spring boot·后端·安全·spring·mybatis·restful