poem_http_common/
response.rs1use poem::{http::StatusCode, Error};
2use poem_openapi::{
3 payload::Json,
4 types::{ParseFromJSON, ToJSON},
5 ApiResponse, Object,
6};
7use serde::{Deserialize, Serialize};
8
9#[derive(Serialize, Deserialize, Debug, Object, Clone)]
10pub struct StatusResponse {
11 pub status: bool,
12}
13
14#[derive(Serialize, Deserialize, Debug, Object, Clone)]
15pub struct RedirectResponse {
16 pub url: String,
17}
18
19pub fn build_error_response(code: StatusCode, msg: &str) -> Error {
20 let err: HttpApiResponse<StatusResponse> = match code {
21 StatusCode::BAD_REQUEST => HttpApiResponse::BadRequest(ErrorResponse::from_str(msg).to_json()),
22 StatusCode::UNAUTHORIZED => HttpApiResponse::Unauthorized(ErrorResponse::from_str(msg).to_json()),
23 StatusCode::FORBIDDEN => HttpApiResponse::Forbidden(ErrorResponse::from_str(msg).to_json()),
24 StatusCode::TOO_MANY_REQUESTS => HttpApiResponse::TooManyRequest(ErrorResponse::from_str(msg).to_json()),
25 StatusCode::NOT_FOUND => HttpApiResponse::NotFound(ErrorResponse::from_str(msg).to_json()),
26 StatusCode::INTERNAL_SERVER_ERROR => {
27 HttpApiResponse::InternalServerError(ErrorResponse::from_str(msg).to_json())
28 }
29 StatusCode::BAD_GATEWAY => HttpApiResponse::BadGateway(ErrorResponse::from_str(msg).to_json()),
30 StatusCode::SERVICE_UNAVAILABLE => HttpApiResponse::ServiceUnavailable(ErrorResponse::from_str(msg).to_json()),
31 _ => HttpApiResponse::InternalServerError(ErrorResponse::from_str(msg).to_json()),
32 };
33
34 Error::from(err)
35}
36
37#[derive(Serialize, Deserialize, Debug, Object, Clone)]
38pub struct ErrorResponse {
39 pub msg: String,
40}
41
42impl ErrorResponse {
43 pub fn from_str(msg: &str) -> Self {
44 Self { msg: msg.to_string() }
45 }
46
47 pub fn to_json(&self) -> Json<Self> {
48 Json(self.clone())
49 }
50}
51
52#[derive(ApiResponse)]
53pub enum HttpApiResponse<T>
54where
55 T: ParseFromJSON + ToJSON + Send + Sync,
56{
57 #[oai(status = 200)]
58 Ok(Json<T>),
59 #[oai(status = 201)]
60 Created(Json<T>),
61 #[oai(status = 301)]
62 MovedPermanently(Json<RedirectResponse>),
63 #[oai(status = 302)]
64 Found(Json<RedirectResponse>),
65 #[oai(status = 400)]
66 BadRequest(Json<ErrorResponse>),
67 #[oai(status = 401)]
68 Unauthorized(Json<ErrorResponse>),
69 #[oai(status = 403)]
70 Forbidden(Json<ErrorResponse>),
71 #[oai(status = 404)]
72 NotFound(Json<ErrorResponse>),
73 #[oai(status = 429)]
74 TooManyRequest(Json<ErrorResponse>),
75 #[oai(status = 500)]
76 InternalServerError(Json<ErrorResponse>),
77 #[oai(status = 502)]
78 BadGateway(Json<ErrorResponse>),
79 #[oai(status = 503)]
80 ServiceUnavailable(Json<ErrorResponse>),
81}