统一接口返回格式为 success/message/data 结构

This commit is contained in:
fish
2026-04-13 20:51:26 +08:00
parent 124dbd019a
commit 7ddba306e8

View File

@@ -2,7 +2,7 @@ use axum::{
extract::State, extract::State,
http::StatusCode, http::StatusCode,
response::Json, response::Json,
routing::post, routing::{get, post},
Router, Router,
}; };
use bcrypt::hash; use bcrypt::hash;
@@ -28,10 +28,15 @@ struct RegisterRequest {
} }
#[derive(Serialize)] #[derive(Serialize)]
struct RegisterResponse { struct ApiResponse<T> {
success: bool, success: bool,
user_id: Option<Uuid>,
message: String, message: String,
data: Option<T>,
}
#[derive(Serialize)]
struct RegisterData {
user_id: Uuid,
} }
#[tokio::main] #[tokio::main]
@@ -51,7 +56,7 @@ async fn main() {
let app = Router::new() let app = Router::new()
.route("/register", post(register_handler)) .route("/register", post(register_handler))
.route("/health", axum::routing::get(health_handler)) .route("/health", get(health_handler))
.with_state(state); .with_state(state);
let port = env::var("SERVICE_PORT").unwrap_or_else(|_| "8080".to_string()); let port = env::var("SERVICE_PORT").unwrap_or_else(|_| "8080".to_string());
@@ -67,17 +72,17 @@ async fn main() {
async fn register_handler( async fn register_handler(
State(state): State<Arc<AppState>>, State(state): State<Arc<AppState>>,
Json(payload): Json<RegisterRequest>, Json(payload): Json<RegisterRequest>,
) -> (StatusCode, Json<RegisterResponse>) { ) -> (StatusCode, Json<ApiResponse<RegisterData>>) {
info!("Registration attempt for user: {}", payload.username); info!("Registration attempt for user: {}", payload.username);
// 参数校验 // 参数校验
if let Err(e) = payload.validate() { if let Err(e) = payload.validate() {
return ( return (
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: format!("Validation error: {}", e), message: format!("Validation error: {}", e),
data: None,
}), }),
); );
} }
@@ -94,10 +99,10 @@ async fn register_handler(
if existing.is_some() { if existing.is_some() {
return ( return (
StatusCode::CONFLICT, StatusCode::CONFLICT,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Username already exists".to_string(), message: "Username already exists".to_string(),
data: None,
}), }),
); );
} }
@@ -109,10 +114,10 @@ async fn register_handler(
warn!("Password hashing failed: {}", e); warn!("Password hashing failed: {}", e);
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Internal error".to_string(), message: "Internal error".to_string(),
data: None,
}), }),
); );
} }
@@ -125,10 +130,10 @@ async fn register_handler(
warn!("Transaction start failed: {}", e); warn!("Transaction start failed: {}", e);
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Internal error".to_string(), message: "Internal error".to_string(),
data: None,
}), }),
); );
} }
@@ -147,10 +152,10 @@ async fn register_handler(
let _ = tx.rollback().await; let _ = tx.rollback().await;
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Registration failed".to_string(), message: "Registration failed".to_string(),
data: None,
}), }),
); );
} }
@@ -169,10 +174,10 @@ async fn register_handler(
let _ = tx.rollback().await; let _ = tx.rollback().await;
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Registration failed".to_string(), message: "Registration failed".to_string(),
data: None,
}), }),
); );
} }
@@ -191,10 +196,10 @@ async fn register_handler(
let _ = tx.rollback().await; let _ = tx.rollback().await;
return ( return (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Registration failed".to_string(), message: "Registration failed".to_string(),
data: None,
}), }),
); );
} }
@@ -204,10 +209,10 @@ async fn register_handler(
info!("User {} registered with id {}", payload.username, user_id); info!("User {} registered with id {}", payload.username, user_id);
( (
StatusCode::CREATED, StatusCode::CREATED,
Json(RegisterResponse { Json(ApiResponse {
success: true, success: true,
user_id: Some(user_id),
message: "User registered successfully".to_string(), message: "User registered successfully".to_string(),
data: Some(RegisterData { user_id }),
}), }),
) )
} }
@@ -215,16 +220,23 @@ async fn register_handler(
warn!("Registration failed: {}", e); warn!("Registration failed: {}", e);
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json(RegisterResponse { Json(ApiResponse {
success: false, success: false,
user_id: None,
message: "Registration failed".to_string(), message: "Registration failed".to_string(),
data: None,
}), }),
) )
} }
} }
} }
async fn health_handler() -> &'static str { async fn health_handler() -> (StatusCode, Json<ApiResponse<()>>) {
"OK" (
StatusCode::OK,
Json(ApiResponse {
success: true,
message: "OK".to_string(),
data: None,
}),
)
} }