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
相关推荐
superman超哥3 小时前
Rust Cargo Run 与 Cargo Test 命令:开发工作流的双引擎
开发语言·后端·rust·cargo run·cargo test·开发工作流·双引擎
superman超哥6 小时前
Rust Trait约束(Trait Bounds):类型能力的精确契约
开发语言·后端·rust·rust trait约束·trait bounds·类型能力·精确契约
superman超哥6 小时前
Rust Where子句的语法:复杂约束的优雅表达
开发语言·后端·rust·rust where子句·复杂约束·优雅表达
superman超哥6 小时前
Rust Cargo Build 编译流程:从源码到二进制的完整旅程
开发语言·后端·rust·编译流程·cargo build·从源码到二进制
Yuer20257 小时前
为什么要用rust做算子执行引擎
人工智能·算法·数据挖掘·rust
古城小栈8 小时前
Rust语言:优势解析与擅长领域深度探索
开发语言·后端·rust
superman超哥8 小时前
Rust Cargo.toml 配置文件详解:项目管理的核心枢纽
开发语言·后端·rust·rust cargo.toml·cargo.toml配置文件
superman超哥9 小时前
Rust 注释与文档注释:代码即文档的工程实践
开发语言·算法·rust·工程实践·rust注释与文档注释·代码即文档
superman超哥10 小时前
Rust 依赖管理与版本控制:Cargo 生态的精妙设计
开发语言·后端·rust·rust依赖管理·rust版本控制·cargo生态
superman超哥10 小时前
Rust 泛型参数的使用:零成本抽象的类型级编程
开发语言·后端·rust·零成本抽象·rust泛型参数·类型级编程