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
相关推荐
码熔burning7 小时前
Spring Security 深度学习(六): RESTful API 安全与 JWT
安全·spring·restful·springsecurity
朝阳5817 小时前
用 Rust + Actix-Web 打造“Hello, WebSocket!”——从握手到回声,只需 50 行代码
前端·websocket·rust
中国胖子风清扬11 小时前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
我就是全世界11 小时前
【存储选型终极指南】RustFS vs MinIO:5大维度深度对决,95%技术团队的选择秘密!
开发语言·分布式·rust·存储
Source.Liu14 小时前
【Python基础】 13 Rust 与 Python 注释对比笔记
开发语言·笔记·python·rust
Source.Liu18 小时前
【Python基础】 19 Rust 与 Python if 语句对比笔记
笔记·python·rust
Source.Liu20 小时前
【Python基础】 18 Rust 与 Python print 函数完整对比笔记
笔记·python·rust
学渣676561 天前
文件传输工具rsync|rust开发环境安装|Ascend实验相关命令
开发语言·后端·rust
咸甜适中2 天前
rust语言 (1.88) egui (0.32.1) 学习笔记(逐行注释)(二十四)窗口颜色、透明度、居中显示
笔记·学习·rust·egui
或与且与或非2 天前
Rust+slint实现一个登录demo
开发语言·rust·状态模式