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
相关推荐
许野平12 小时前
Rust: Warp RESTful API 如何得到客户端IP?
tcp/ip·rust·restful·ip地址
许野平16 小时前
Rust:Result 和 Error
开发语言·后端·rust·error·result
百锦再18 小时前
Web后端开发技术:RESTful 架构详解
前端·架构·restful
Freestyle Coding18 小时前
使用rust自制操作系统内核
c语言·汇编·microsoft·rust·操作系统
许野平2 天前
Rust 编译器使用的 C++ 编译器吗?
c++·rust
怪我冷i2 天前
Rust GUI框架Tauri V1 入门
rust
新知图书2 天前
Rust的常量
算法·机器学习·rust
白总Server2 天前
php语言基本语法
开发语言·ide·后端·golang·rust·github·php
凄凄迷人2 天前
前端基于Rust实现的Wasm进行图片压缩的技术文档
前端·rust·wasm·图片压缩
winddevil2 天前
[rCore学习笔记 027]地址空间
rust·嵌入式·rcore