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
相关推荐
萧曵 丶2 小时前
Rust 中的返回类型
开发语言·后端·rust
浪裡遊4 小时前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
受之以蒙5 小时前
Rust & WASM 之 wasm-bindgen 基础:让 Rust 与 JavaScript 无缝对话
前端·笔记·rust
Elixin5 小时前
第一章:环境搭建
rust
Pomelo_刘金1 天前
Rust 宣布发布1.88.0
rust
寻月隐君1 天前
告别 Vec!掌握 Rust bytes 库,解锁零拷贝的真正威力
后端·rust·github
大卫小东(Sheldon)1 天前
GIM 1.5发布了! 支持Windows系统了
git·ai·rust
寻月隐君1 天前
告别竞态条件:基于 Axum 和 Serde 的 Rust 并发状态管理最佳实践
后端·rust·github
成遇11 天前
在Vscode中安装Sass并配置
vscode·rust·sass
止观止11 天前
Rust智能指针演进:从堆分配到零复制的内存管理艺术
开发语言·后端·rust