StatusCode
概述axum::http::StatusCode
提供了 HTTP 状态码的枚举,涵盖了从 100
到 599
的所有标准状态码。
通过使用这些状态码,您可以精确地控制 HTTP 响应的语义,例如成功、客户端错误、服务器错误等。
200 OK
201 Created
204 No Content
301 Moved Permanently
302 Found
304 Not Modified
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable
StatusCode
在 Axum 中,您可以在处理函数中返回 Result
类型,其中 Ok
包含 Response
或 axum::response::Response
,而 Err
包含 StatusCode
或自定义错误类型。
rust
use axum::{
Router,
routing::get,
http::StatusCode,
response::Response,
};
use std::net::SocketAddr;
async fn handler() -> Result {
// 业务逻辑
Ok((
StatusCode::OK,
"Hello, World!".to_string(),
).into_response())
}
#[tokio::main]
async fn main() {
// 构建路由
let app = Router::new().route("/", get(handler));
// 绑定地址并运行
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
IntoResponse
特性Axum 的 IntoResponse
特性允许您将任何实现了该特性的类型转换为 HTTP 响应。
通过实现 IntoResponse
,您可以自定义更复杂的响应结构。
rust
use axum::{
response::{IntoResponse, Response},
http::StatusCode,
};
use serde::Serialize;
#[derive(Serialize)]
struct ApiResponse {
data: Option,
message: String,
}
impl IntoResponse for ApiResponse
where
T: Serialize,
{
fn into_response(self) -> Response {
let body = serde_json::to_string(&self).unwrap();
let status = match self.message.as_str() {
"success" => StatusCode::OK,
"created" => StatusCode::CREATED,
"not_found" => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, body).into_response()
}
}
async fn get_user() -> impl IntoResponse {
let user = fetch_user().await;
if user.is_some() {
ApiResponse {
data: user,
message: "success".to_string(),
}
} else {
ApiResponse {
data: None,
message: "not_found".to_string(),
}
}
}
使用 StatusCode
进行错误处理,可以使错误响应更加语义化。例如:
rust
use axum::{
response::{IntoResponse, Response},
http::StatusCode,
Json,
};
use serde::Serialize;
#[derive(Serialize)]
struct ErrorResponse {
error: String,
}
impl IntoResponse for ErrorResponse {
fn into_response(self) -> Response {
let body = serde_json::to_string(&self).unwrap();
(StatusCode::BAD_REQUEST, Json(self)).into_response()
}
}
async fn create_user() -> Result {
// 假设创建用户失败
Err(ErrorResponse {
error: "User already exists".to_string(),
})
}
201 Created
用于成功创建资源,204 No Content
用于成功但无返回内容,400 Bad Request
用于客户端请求错误等。200 OK
或 500 Internal Server Error
,确保每个状态码都有明确的语义。ApiResponse
,确保所有 API 端点的响应结构一致。304 Not Modified
)和缓存策略,提高性能。以下是一个完整的 Axum 应用示例,展示了如何使用 StatusCode
来处理不同的 HTTP 请求和响应。
rust
use axum::{
routing::{get, post},
Router,
response::{IntoResponse, Response},
http::StatusCode,
Json,
};
use serde::Serialize;
use std::net::SocketAddr;
#[derive(Serialize)]
struct ApiResponse {
data: Option,
message: String,
}
impl IntoResponse for ApiResponse
where
T: Serialize,
{
fn into_response(self) -> Response {
let body = serde_json::to_string(&self).unwrap();
let status = match self.message.as_str() {
"success" => StatusCode::OK,
"created" => StatusCode::CREATED,
"not_found" => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, body).into_response()
}
}
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
async fn get_user() -> impl IntoResponse {
let user = fetch_user().await;
if user.is_some() {
ApiResponse {
data: user,
message: "success".to_string(),
}
} else {
ApiResponse {
data: None,
message: "not_found".to_string(),
}
}
}
async fn create_user(Json(payload): Json) -> impl IntoResponse {
// 假设用户创建成功
let user = payload;
// 实际应用中,这里应将用户信息保存到数据库
ApiResponse {
data: Some(user),
message: "created".to_string(),
}
}
async fn fetch_user() -> Option {
// 从数据库或其他数据源获取用户信息
Some(User {
id: 1,
name: "Alice".to_string(),
})
}
#[tokio::main]
async fn main() {
// 构建路由
let app = Router::new()
.route("/", get(get_user))
.route("/users", post(create_user));
// 绑定地址并运行
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
通过使用 axum::http::StatusCode
,您可以精确地控制 HTTP 响应的状态码,实现更细粒度的错误处理和响应管理。
结合 Axum 的 IntoResponse
特性,您可以创建统一且语义化的响应结构,提高 API 的可维护性和客户端的易用性。
关键要点的总结:
通过这些策略,您可以构建一个高效、安全且易于维护的 Rust Web 应用。
联系方式:https://t.me/XMOhost26
交流技术群:https://t.me/owolai008