Hyper for Rust:完整指南与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是Hyper以及为什么需要它

\n\n

Hyper 是一个用 Rust 编写的高性能异步 HTTP 库,专为 Rust 语言设计。它是 Rust 生态系统中用于处理 HTTP/1 和 HTTP/2 协议最流行且备受推崇的库之一。Hyper 同时提供客户端和服务器端功能,使开发者能够构建快速、安全且高效的 Web 应用程序和 API。

\n\n

使用 Hyper 的主要原因:

\n
    \n
  • 性能:Hyper 基于 Tokio 异步运行时构建,采用非阻塞 I/O,能够以极低的资源消耗处理数千个并发连接。
  • \n
  • 安全性:Rust 在编译阶段保证内存安全,Hyper 遵循这一原则,最大限度地降低内存泄漏和数据竞争的风险。
  • \n
  • 灵活性:该库提供对 HTTP 连接的低层级控制,允许实现几乎任何请求处理逻辑。
  • \n
  • 兼容性:Hyper 是许多其他流行 Rust 框架(如 Warp、Axum 和 Tide)的基础。
  • \n
  • HTTP/2 支持:内置 HTTP/2 支持,更高效地利用网络资源。
  • \n
\n\n

Hyper 非常适合构建微服务、代理服务器、API 网关以及任何对速度和可靠性有要求的网络应用程序。

\n\n

安装 Hyper

\n\n

通过 Cargo 包管理器将 Hyper 安装到 Rust 项目中。在 Cargo.toml 文件中添加以下依赖:

\n\n
[dependencies]\nhyper = { version = "1.5", features = ["full"] }\ntokio = { version = "1", features = ["full"] }\nserde = { version = "1.0", features = ["derive"] }\nserde_json = "1.0"
\n\n

依赖说明:

\n
    \n
  • hyper:主库,启用所有功能(服务器、客户端、HTTP/2)。
  • \n
  • tokio:Hyper 运行所需的异步运行时。
  • \n
  • serde 和 serde_json:用于数据的序列化/反序列化(示例中会用到)。
  • \n
\n\n

添加依赖后,运行 cargo build 命令以下载并编译这些库。

\n\n

快速入门:简单的 HTTP 服务器

\n\n

创建一个最小的 HTTP 服务器,对任何请求都返回 "Hello, World!"。创建 src/main.rs 文件,内容如下:

\n\n
use hyper::service::{service_fn, Service};\nuse hyper::{Body, Request, Response, Server};\nuse std::convert::Infallible;\nuse std::future::Future;\nuse std::pin::Pin;\nuse std::task::{Context, Poll};\n\n// 定义我们的服务类型\nstruct HelloWorld;\n\nimpl Service<Request<Body>> for HelloWorld {\n    type Response = Response<Body>;\n    type Error = Infallible;\n    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;\n\n    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n        Poll::Ready(Ok(()))\n    }\n\n    fn call(&mut self, _req: Request<Body>) -> Self::Future {\n        let response = Response::builder()\n            .status(200)\n            .header("Content-Type", "text/plain")\n            .body(Body::from("Hello, World!"))\n            .unwrap();\n\n        Box::pin(async { Ok(response) })\n    }\n}\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {\n    let addr = ([127, 0, 0, 1], 3000).into();\n    let server = Server::bind(&addr).serve(service_fn(|req| async move {\n        let response = Response::builder()\n            .status(200)\n            .header("Content-Type", "text/plain")\n            .body(Body::from("Hell                    

推荐