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(),
}
}