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
相关推荐
Source.Liu1 天前
【Rust】枚举(Enum)详解
rust
唐装鼠1 天前
Rust 类型转换语法大全(deepseek)
rust
ServBay1 天前
7个Rust写法让代码干净卫生又高效
后端·rust
Source.Liu1 天前
【Rust】变量系统详解
rust
Source.Liu1 天前
【Rust】数组与向量:集合类型全解
rust
唐装鼠1 天前
Rust Box<T> 和引用(deepseek)
开发语言·rust
Source.Liu1 天前
【Rust】结构体(Struct)详解
rust
秋邱1 天前
Java面向对象进阶:封装、继承、多态的实现逻辑与实战案例
java·开发语言·后端·spring cloud·ar·restful
isyuah1 天前
Miko v0.7 发布:我写的一个 Rust Web 框架,虽然还是个玩具
后端·rust
isyuah1 天前
Miko 框架系列(十四):集成测试
后端·rust