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
相关推荐
muyouking112 小时前
4.Rust+Axum Tower 中间件实战:从集成到自定义
开发语言·中间件·rust
Source.Liu3 小时前
【TeamFlow】4.2 Yew库详细介绍
rust·yew
勇敢牛牛_3 小时前
【MRAG】使用RAG技术增强AI回复的实时性和准确性
rust·知识库·rag
techdashen6 小时前
性能比拼: Rust vs Zig vs Go
开发语言·golang·rust
muyouking119 小时前
9.Rust+Axum 测试驱动开发与性能优化全攻略
驱动开发·性能优化·rust
阿阳热爱前端11 小时前
BongoCat 桌宠全新升级!开源 × 跨平台,快来撸猫!
前端·rust·app
阿廖沙102415 小时前
前端开发工程师的Rust入门
rust
xixixiLucky16 小时前
RESTful学习笔记(一)
后端·restful
pumpkin845141 天前
学习笔记十七——Rust 支持面向对象编程吗?
笔记·学习·rust
Source.Liu1 天前
【TeamFlow】3 Rust 与 WebAssembly (Wasm) 深度应用指南
rust·wasm