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
相关推荐
itmigrate13 小时前
Rust 里的所有权误区:不是不写 clone 就叫高性能
开发语言·后端·rust
小灰灰搞电子18 小时前
Rust+Slint 实现动态流光边框源码分享
开发语言·前端·rust·流光边框
Bigger18 小时前
开源了一个"先预览、能反悔"的文件整理工具,聊聊背后的工程细节
rust·开源·app
m0_6399069419 小时前
RESTful API 接口设计规范:资源导向、HTTP 语义、统一返回格式、避坑指南
http·restful·设计规范
老王IT20 小时前
Rust开发环境搭建教程
开发语言·后端·rust
@大迁世界1 天前
告别 Go,拥抱 Rust
开发语言·golang·rust
低调滴开发2 天前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust
乌暮2 天前
综合案例:宠物电商系统
java·开发语言·spring·mvc·restful·1024程序员节
小灰灰搞电子2 天前
Rust+Slint 实现高级动态消息提示框源码分享
开发语言·rust
qq_406981032 天前
大白话rust系列08 当变量遮蔽遇上引用,探究变量遮蔽的本质
开发语言·后端·rust