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
相关推荐
ServBay16 小时前
这9个高性能的Rust库不容错过
后端·rust
Rust研习社17 小时前
Rust 堆内存指针 Box 详解
开发语言·后端·rust
Jacky-00818 小时前
Rust安装(MinGw64编译器安装)
开发语言·后端·rust
咚为1 天前
深入理解 Rust 的静态分发与动态分发:从 `impl Trait` 到 `dyn Trait`
开发语言·后端·rust
中国胖子风清扬1 天前
基于GPUI框架构建现代化待办事项应用:从架构设计到业务落地
java·spring boot·macos·小程序·rust·uni-app·web app
m0_694845572 天前
CRUD (Nestjsx)部署教程:自动生成RESTful接口
服务器·人工智能·后端·开源·自动化·restful
爱分享的阿Q2 天前
RustWebAssembly商用元年从实验到生产完整迁移指南
rust·web·wasm
大卫小东(Sheldon)2 天前
Rudist v0.5.1 发布:AI 驱动的 Redis 客户端,更快、更直观
rust·rudist
潇洒畅想2 天前
1.2 希腊字母速查表 + 公式阅读实战
java·人工智能·python·算法·rust·云计算