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
相关推荐
Amos_Web7 小时前
Solana 智能合约编译问题排查与修复总结
前端·rust·区块链
代码羊羊7 小时前
rust-字符串(切片)、元组、结构体、枚举、数组
开发语言·后端·rust
好家伙VCC8 小时前
**发散创新:用 Rust实现游戏日引擎核心模块——从事件驱动到多线程调度的实战
java·开发语言·python·游戏·rust
RFCEO13 小时前
Rust编程基础课 第1课时:Rust简介与环境搭建 STM32 RUST嵌入式编程实战
stm32·嵌入式硬件·rust·probe-rs·rust工具链·rustup、cargo·stm32 rust适配
techdashen1 天前
每次 `cargo build` 背后,有人在默默撑着这一切
rust
Binarydog_Lee1 天前
Rust 核心机制:所有权、借用与生命周期
开发语言·rust
卜夋1 天前
Rust 学习笔记 - Day 6: 引用与借用
后端·rust