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
相关推荐
Kiri霧2 分钟前
Rust开发环境搭建
开发语言·后端·rust
QX_hao4 小时前
【Go】--数组和切片
后端·golang·restful
xuejianxinokok12 小时前
什么是代数类型 ? java为什么要添加record,Sealed class 和增强switch ?
后端·rust
Kiri霧15 小时前
在actix-web中创建一个提取器
后端·rust·web
^_^ 纵歌15 小时前
rust主要用于哪些领域
开发语言·后端·rust
l1t1 天前
测试DuckDB电子表格读取插件rusty_sheet 0.2版
数据库·rust·插件·xlsx·duckdb
嚴寒2 天前
被10个终端窗口逼疯后,我用Rust写了个零依赖跨平台终端Agent启动神器
rust·agent
alwaysrun2 天前
Rust中模式匹配
rust·match·模式匹配·if let·while let·值绑定
编码浪子3 天前
Dioxus hot-dog 总结
rust
光影少年3 天前
rust生态及学习路线,应用领域
开发语言·学习·rust