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
相关推荐
Dynadot_tech1 小时前
使用RESTfulAPI有效率地管理Dynadot域名,Webhook功能上线
api·restful·域名·restful api·dynadot·域名管理
努力攻坚操作系统9 小时前
重新理解 RESTful:从理论约束到工程实践
后端·restful
星秀日9 小时前
rust学习入门
开发语言·学习·rust
mCell12 小时前
我把默认的 code . 换成了 zed .
rust·visual studio code·trae
Rust研习社12 小时前
MSRV 是什么?一文说清楚
后端·rust·编程语言
特立独行的猫a13 小时前
Rust+ Tauri实现漂亮小巧的Mqtt客户端工具--AtomMQTT Client 实现详解
开发语言·后端·mqtt·rust
咸甜适中13 小时前
rust语言学习笔记Trait(十三)Borrow、BorrowMut(借用)
笔记·学习·rust
朝阳58113 小时前
树莓派跑了个 M3U8 下载服务,内存从 600MB 降到 2MB
性能优化·rust
Tony Bai14 小时前
从 Go 迁移到 Rust
开发语言·后端·golang·rust