1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use axum::{
http::{header, HeaderValue, StatusCode},
response::{IntoResponse, Response},
};
use bytes::{BufMut, Bytes, BytesMut};
use serde::Serialize;
#[cfg_attr(docsrs, doc(cfg(feature = "erased-json")))]
#[derive(Debug)]
pub struct ErasedJson(serde_json::Result<Bytes>);
impl ErasedJson {
pub fn new<T: Serialize>(val: T) -> Self {
let mut bytes = BytesMut::with_capacity(128);
Self(serde_json::to_writer((&mut bytes).writer(), &val).map(|_| bytes.freeze()))
}
pub fn pretty<T: Serialize>(val: T) -> Self {
let mut bytes = BytesMut::with_capacity(128);
Self(serde_json::to_writer_pretty((&mut bytes).writer(), &val).map(|_| bytes.freeze()))
}
}
impl IntoResponse for ErasedJson {
fn into_response(self) -> Response {
match self.0 {
Ok(bytes) => (
[(
header::CONTENT_TYPE,
HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),
)],
bytes,
)
.into_response(),
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(),
}
}
}