Rust HTTP服务器库deno_http的使用,构建高性能Web服务和API的Rust插件库
Rust HTTP服务器库deno_http的使用,构建高性能Web服务和API的Rust插件库
deno_http是一个基于Fetch API原语实现的服务器端HTTP库。
安装
在项目目录中运行以下Cargo命令:
cargo add deno_http
或在Cargo.toml中添加以下行:
deno_http = "0.210.0"
完整示例代码
下面是一个使用deno_http构建简单HTTP服务器的完整示例:
use deno_http::{serve, Request, Response, StatusCode};
async fn handler(req: Request) -> Result<Response, std::io::Error> {
// 根据请求路径返回不同响应
match req.path() {
"/" => Ok(Response::new(StatusCode::OK).body("Hello, World!")),
"/api" => Ok(Response::new(StatusCode::OK).body("API endpoint")),
_ => Ok(Response::new(StatusCode::NOT_FOUND).body("Not Found")),
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 创建HTTP服务器并监听3000端口
let server = serve("127.0.0.1:3000", handler).await?;
println!("Server running at http://127.0.0.1:3000/");
// 等待服务器关闭
server.await?;
Ok(())
}
更复杂的API示例
use deno_http::{serve, Request, Response, StatusCode, Method};
use serde_json::json;
async fn api_handler(req: Request) -> Result<Response, std::io::Error> {
match (req.method(), req.path()) {
(Method::GET, "/users") => {
// 模拟获取用户列表
let users = json!([
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]);
Ok(Response::new(StatusCode::OK)
.header("Content-Type", "application/json")
.body(users.to_string()))
}
(Method::POST, "/users") => {
// 处理创建用户请求
Ok(Response::new(StatusCode::CREATED)
.body("User created"))
}
(Method::GET, path) if path.starts_with("/users/") => {
// 处理获取单个用户请求
let user_id = path.trim_start_matches("/users/");
let user = json!({"id": user_id, "name": "Example User"});
Ok(Response::new(StatusCode::OK)
.header("Content-Type", "application/json")
.body(user.to_string()))
}
_ => Ok(Response::new(StatusCode::NOT_FOUND)
.body("Endpoint not found"))
}
}
#[tokio::main]
async fn main() {
serve("127.0.0.1:3000", api_handler).await.unwrap();
}
完整示例demo
下面是一个结合文件服务和JSON API的完整示例:
use deno_http::{serve, Request, Response, StatusCode, Method};
use serde_json::json;
use std::path::Path;
async fn file_handler(req: Request) -> Result<Response, std::io::Error> {
match (req.method(), req.path()) {
// 首页路由
(Method::GET, "/") => {
Ok(Response::new(StatusCode::OK)
.header("Content-Type", "text/html")
.body("<h1>欢迎来到Rust服务器</h1><p>访问/api/data获取数据</p>"))
}
// JSON API路由
(Method::GET, "/api/data") => {
let data = json!({
"status": "success",
"data": {
"items": [1, 2, 3],
"message": "Hello from Rust API"
}
});
Ok(Response::new(StatusCode::OK)
.header("Content-Type", "application/json")
.body(data.to_string()))
}
// 文件服务路由
(Method::GET, path) if path.starts_with("/static/") => {
let file_path = format!(".{}", path);
if Path::new(&file_path).exists() {
let content = std::fs::read_to_string(file_path)?;
Ok(Response::new(StatusCode::OK).body(content))
} else {
Ok(Response::new(StatusCode::NOT_FOUND)
.body("File not found"))
}
}
// 默认404路由
_ => Ok(Response::new(StatusCode::NOT_FOUND)
.body("404 Not Found"))
}
}
#[tokio::main]
async fn main() {
println!("启动服务器在 http://127.0.0.1:8080");
serve("127.0.0.1:8080", file_handler).await.unwrap();
}
这个库提供了简洁的API来构建高性能的Web服务和API,适合作为Rust插件库使用。
1 回复
Rust HTTP服务器库deno_http的使用指南
deno_http
是一个基于Rust构建的高性能HTTP服务器库,专为构建Web服务和API而设计。它最初是为Deno运行时开发的HTTP基础设施,后来被提取为一个独立的Rust库。
主要特性
- 高性能:基于Rust的异步运行时构建
- 简单易用:提供直观的API设计
- 轻量级:不依赖复杂的框架
- 跨平台支持:可在多种操作系统上运行
基本使用方法
1. 添加依赖
首先在Cargo.toml
中添加依赖:
[dependencies]
deno_http = "0.1.0"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0" # 用于JSON处理
2. 创建基本HTTP服务器
use deno_http::{serve, HttpRequest, HttpResponse};
use std::convert::Infallible;
#[tokio::main]
async fn main() -> Result<(), Infallible> {
// 绑定到本地8080端口
let addr = "127.0.0.1:8080".parse().unwrap();
// 启动HTTP服务器
serve(addr, |req: HttpRequest| async move {
// 路由匹配
match req.path() {
"/" => HttpResponse::ok("Hello, World!"),
"/api" => HttpResponse::json(&serde_json::json!({"message": "API response"})),
_ => HttpResponse::not_found(),
}
}).await
}
3. 处理不同HTTP方法
use deno_http::{serve, HttpRequest, HttpResponse, Method};
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
serve(addr, |req: HttpRequest| async move {
// 同时匹配HTTP方法和路径
match (req.method(), req.path()) {
(Method::GET, "/users") => {
// 获取用户列表逻辑
HttpResponse::ok("User list")
},
(Method::POST, "/users") => {
// 处理POST请求体
if let Some(body) = req.body() {
println!("Received user data: {:?}", body);
}
// 返回201 Created状态码
HttpResponse::created().body("User created")
},
_ => HttpResponse::not_found(),
}
}).await.unwrap();
}
高级功能
1. 中间件支持
use deno_http::{serve, HttpRequest, HttpResponse, Middleware, Next};
// 自定义日志中间件
async fn logger_middleware(req: HttpRequest, next: Next) -> HttpResponse {
println!("[LOG] {} {}", req.method(), req.path());
// 调用下一个中间件或处理程序
next.run(req).await
}
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
// 创建中间件链
let middleware = Middleware::new()
.with(logger_middleware);
// 使用中间件包装处理函数
serve(addr, middleware.wrap(|req| async move {
HttpResponse::ok("Hello with logging!")
})).await.unwrap();
}
2. 路由处理
use deno_http::{serve, HttpRequest, HttpResponse};
use std::collections::HashMap;
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
// 创建路由表
let mut routes = HashMap::new();
routes.insert("/about", about_handler);
routes.insert("/contact", contact_handler);
serve(addr, move |req| {
// 查找匹配的路由处理函数
let handler = routes.get(req.path()).unwrap_or(¬_found_handler);
handler(req)
}).await.unwrap();
}
// 关于页面处理函数
async fn about_handler(_req: HttpRequest) -> HttpResponse {
HttpResponse::ok("About page")
}
// 联系页面处理函数
async fn contact_handler(_req: HttpRequest) -> HttpResponse {
HttpResponse::ok("Contact page")
}
// 404处理函数
async fn not_found_handler(_req: HttpRequest) -> HttpResponse {
HttpResponse::not_found()
}
3. 文件服务
use deno_http::{serve, HttpRequest, HttpResponse};
use std::path::Path;
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
serve(addr, |req| async move {
// 处理静态文件请求
if req.path().starts_with("/static/") {
let file_path = Path::new(".").join(&req.path()[1..]);
// 检查文件是否存在
if file_path.exists() {
// 异步读取文件内容
if let Ok(content) = tokio::fs::read(&file_path).await {
return HttpResponse::ok(content)
.with_header("Content-Type", "application/octet-stream");
}
}
return HttpResponse::not_found();
}
// 默认返回主页
HttpResponse::ok("Main page")
}).await.unwrap();
}
完整示例:带中间件的REST API服务
use deno_http::{serve, HttpRequest, HttpResponse, Middleware, Next, Method};
use serde_json::json;
use std::sync::Arc;
use tokio::sync::Mutex;
// 自定义数据结构
struct AppState {
counter: Mutex<i32>,
}
// 状态共享中间件
async fn state_middleware(req: HttpRequest, next: Next<AppState>) -> HttpResponse {
let state = req.extensions().get::<Arc<AppState>>().unwrap();
let mut counter = state.counter.lock().await;
*counter += 1;
println!("Request count: {}", *counter);
next.run(req).await
}
// 认证中间件
async fn auth_middleware(req: HttpRequest, next: Next<AppState>) -> HttpResponse {
if let Some(auth) = req.headers().get("Authorization") {
if auth == "Bearer secret" {
return next.run(req).await;
}
}
HttpResponse::unauthorized().body("Unauthorized")
}
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
let state = Arc::new(AppState {
counter: Mutex::new(0),
});
// 创建中间件链
let middleware = Middleware::new()
.with(state_middleware)
.with(auth_middleware)
.state(state);
serve(addr, middleware.wrap(|req| async move {
match (req.method(), req.path()) {
(Method::GET, "/api/data") => {
HttpResponse::json(&json!({
"status": "ok",
"data": [1, 2, 3]
}))
},
(Method::POST, "/api/data") => {
if let Some(body) = req.body() {
println!("Received data: {:?}", body);
}
HttpResponse::created().json(&json!({"status": "created"}))
},
_ => HttpResponse::not_found(),
}
})).await.unwrap();
}
性能优化建议
-
启用release模式:使用
cargo run --release
运行服务器以获得最佳性能 -
合理使用连接池:对于数据库等资源,使用连接池减少连接开销
-
异步处理:确保所有I/O操作都是异步的,避免阻塞事件循环
-
响应压缩:对大型响应启用压缩
use deno_http::{serve, HttpRequest, HttpResponse};
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
serve(addr, |req| async move {
let large_data = vec![0u8; 1024 * 1024]; // 1MB数据
HttpResponse::ok(large_data)
.with_header("Content-Encoding", "gzip")
}).await.unwrap();
}
总结
deno_http
提供了一个轻量级但功能强大的基础来构建Rust HTTP服务器。它特别适合需要高性能和低开销的场景,同时保持了API的简洁性。通过结合Rust的异步特性和生态系统的其他库,可以构建出高效可靠的Web服务和API。