meta_srv/service/admin/
util.rs1use std::fmt::Debug;
16
17use axum::http::StatusCode;
18use axum::response::{IntoResponse, Response};
19use serde::Serialize;
20use snafu::ResultExt;
21use tonic::codegen::http;
22
23use crate::error::{self, Result};
24
25pub fn to_text_response(text: &str) -> Result<http::Response<String>> {
27 http::Response::builder()
28 .header("Content-Type", "text/plain")
29 .status(http::StatusCode::OK)
30 .body(text.to_string())
31 .context(error::InvalidHttpBodySnafu)
32}
33
34pub fn to_json_response<T>(response: T) -> Result<http::Response<String>>
36where
37 T: Serialize + Debug,
38{
39 let response = serde_json::to_string(&response).context(error::SerializeToJsonSnafu {
40 input: format!("{response:?}"),
41 })?;
42 http::Response::builder()
43 .header("Content-Type", "application/json")
44 .status(http::StatusCode::OK)
45 .body(response)
46 .context(error::InvalidHttpBodySnafu)
47}
48
49pub fn to_not_found_response() -> Result<http::Response<String>> {
51 http::Response::builder()
52 .status(http::StatusCode::NOT_FOUND)
53 .body("".to_string())
54 .context(error::InvalidHttpBodySnafu)
55}
56
57pub(crate) struct ErrorHandler<E>(E)
59where
60 E: std::error::Error + Send + Sync + Sized;
61
62impl<E> ErrorHandler<E>
63where
64 E: std::error::Error + Send + Sync + Sized,
65{
66 pub(crate) fn new(error: E) -> Self {
67 Self(error)
68 }
69}
70
71impl<E> IntoResponse for ErrorHandler<E>
72where
73 E: std::error::Error + Send + Sync + Sized,
74{
75 fn into_response(self) -> Response {
76 (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
77 }
78}