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
相关推荐
Captaincc9 小时前
基于Prompt 的DevOps 与终端重塑
warp
DevOps00810 小时前
在 Azure Linux 上安装 RustFS
rust·minio·分布式存储·s3·rustfs
hweiyu0010 小时前
Rust 简介
rust
萧曵 丶10 小时前
Rust中Option和Result详解
开发语言·后端·rust·option·result
火柴就是我14 小时前
每日见闻之Rust中 trait 的孤儿规则
android·rust
白仑色16 小时前
Spring Boot + Thymeleaf + RESTful API 前后端整合完整示例
spring boot·后端·restful·thymeleaf·restfulapi
zstar-_20 小时前
Hello, Tauri!
rust
我是前端小学生1 天前
Rust中的Vec数据结构介绍
rust
小马哥聊DevSecOps2 天前
RustFS:Rust 语言编写的分布式存储系统初探
rust