响应处理
响应处理
本文将介绍 Silent 框架中的响应处理机制,包括如何返回不同类型的响应数据。
基本响应
Silent 框架支持多种响应类型,最简单的是返回字符串:
use silent::prelude::*;
#[handler]
async fn hello() -> &'static str {
"Hello, world!"
}
#[handler]
async fn greeting(name: String) -> String {
format!("Hello, {}!", name)
}响应处理
JSON 响应
使用 Json 包装器可以轻松返回 JSON 数据:
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
email: String,
}
#[handler]
async fn get_user() -> Json<User> {
Json(User {
id: 1,
name: "Alice".to_string(),
email: "[email protected]".to_string(),
})
}
#[handler]
async fn list_users() -> Json<Vec<User>> {
let users = vec![
User {
id: 1,
name: "Alice".to_string(),
email: "[email protected]".to_string(),
},
User {
id: 2,
name: "Bob".to_string(),
email: "[email protected]".to_string(),
},
];
Json(users)
}响应处理
完整示例
这是一个综合示例,展示了不同类型的响应处理:
use serde::Serialize;
use silent::prelude::*;
#[derive(Serialize)]
struct ApiResponse<T> {
code: i32,
message: String,
data: Option<T>,
}
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
#[handler]
async fn success_response() -> Json<ApiResponse<User>> {
Json(ApiResponse {
code: 0,
message: "Success".to_string(),
data: Some(User {
id: 1,
name: "Alice".to_string(),
}),
})
}
#[handler]
async fn error_response() -> Result<Json<ApiResponse<()>>> {
Err(Error::new("Invalid request")
.with_status(StatusCode::BAD_REQUEST))
}
#[handler]
async fn conditional_response(query: Query<HashMap<String, String>>) -> Response {
match query.get("type") {
Some("json") => Response::builder()
.header("Content-Type", "application/json")
.body("{\"status\": \"ok\"}")
.unwrap(),
Some("html") => Response::builder()
.header("Content-Type", "text/html")
.body("<h1>Hello</h1>")
.unwrap(),
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("Invalid type")
.unwrap(),
}
}这个示例展示了如何处理成功和错误响应,以及如何根据请求参数返回不同格式的响应。代码结构清晰,易于维护和扩展。
Last updated
Was this helpful?