|
| 1 | +use alloc::boxed::Box; |
| 2 | +use alloc::string::{String, ToString}; |
| 3 | + |
| 4 | +use axum::async_trait; |
| 5 | +use axum::extract::rejection::BytesRejection; |
| 6 | +use axum::extract::{FromRequest, Request}; |
| 7 | +use axum::http::header::{self, HeaderValue}; |
| 8 | +use axum::http::{HeaderMap, StatusCode}; |
| 9 | +use axum::response::{IntoResponse, Response}; |
| 10 | +use bytes::{BufMut, Bytes, BytesMut}; |
| 11 | +use musli::de::DecodeOwned; |
| 12 | +use musli::json::Encoding; |
| 13 | +use musli::mode::Text; |
| 14 | +use musli::Encode; |
| 15 | + |
| 16 | +const ENCODING: Encoding = Encoding::new(); |
| 17 | + |
| 18 | +trait JsonEncoding {} |
| 19 | + |
| 20 | +/// A rejection from the JSON extractor. |
| 21 | +pub enum JsonRejection { |
| 22 | + ContentType, |
| 23 | + Report(String), |
| 24 | + BytesRejection(BytesRejection), |
| 25 | +} |
| 26 | + |
| 27 | +impl From<BytesRejection> for JsonRejection { |
| 28 | + #[inline] |
| 29 | + fn from(rejection: BytesRejection) -> Self { |
| 30 | + JsonRejection::BytesRejection(rejection) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl IntoResponse for JsonRejection { |
| 35 | + fn into_response(self) -> Response { |
| 36 | + let status; |
| 37 | + let body; |
| 38 | + |
| 39 | + match self { |
| 40 | + JsonRejection::ContentType => { |
| 41 | + status = StatusCode::UNSUPPORTED_MEDIA_TYPE; |
| 42 | + body = String::from("Expected request with `Content-Type: application/json`"); |
| 43 | + } |
| 44 | + JsonRejection::Report(report) => { |
| 45 | + status = StatusCode::BAD_REQUEST; |
| 46 | + body = report; |
| 47 | + } |
| 48 | + JsonRejection::BytesRejection(rejection) => { |
| 49 | + return rejection.into_response(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + ( |
| 54 | + status, |
| 55 | + [( |
| 56 | + header::CONTENT_TYPE, |
| 57 | + HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()), |
| 58 | + )], |
| 59 | + body, |
| 60 | + ) |
| 61 | + .into_response() |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +/// Encode the given value as JSON. |
| 66 | +pub struct Json<T>(pub T); |
| 67 | + |
| 68 | +#[async_trait] |
| 69 | +impl<T, S> FromRequest<S> for Json<T> |
| 70 | +where |
| 71 | + T: DecodeOwned<Text>, |
| 72 | + S: Send + Sync, |
| 73 | +{ |
| 74 | + type Rejection = JsonRejection; |
| 75 | + |
| 76 | + async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { |
| 77 | + if !json_content_type(req.headers()) { |
| 78 | + return Err(JsonRejection::ContentType); |
| 79 | + } |
| 80 | + |
| 81 | + let bytes = Bytes::from_request(req, state).await?; |
| 82 | + Self::from_bytes(&bytes) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +fn json_content_type(headers: &HeaderMap) -> bool { |
| 87 | + let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) { |
| 88 | + content_type |
| 89 | + } else { |
| 90 | + return false; |
| 91 | + }; |
| 92 | + |
| 93 | + let content_type = if let Ok(content_type) = content_type.to_str() { |
| 94 | + content_type |
| 95 | + } else { |
| 96 | + return false; |
| 97 | + }; |
| 98 | + |
| 99 | + let mime = if let Ok(mime) = content_type.parse::<mime::Mime>() { |
| 100 | + mime |
| 101 | + } else { |
| 102 | + return false; |
| 103 | + }; |
| 104 | + |
| 105 | + let is_json_content_type = mime.type_() == "application" |
| 106 | + && (mime.subtype() == "json" || mime.suffix().map_or(false, |name| name == "json")); |
| 107 | + |
| 108 | + is_json_content_type |
| 109 | +} |
| 110 | + |
| 111 | +impl<T> IntoResponse for Json<T> |
| 112 | +where |
| 113 | + T: Encode<Text>, |
| 114 | +{ |
| 115 | + fn into_response(self) -> Response { |
| 116 | + // Use a small initial capacity of 128 bytes like serde_json::to_vec |
| 117 | + // https://docs.rs/serde_json/1.0.82/src/serde_json/ser.rs.html#2189 |
| 118 | + let mut buf = BytesMut::with_capacity(128).writer(); |
| 119 | + |
| 120 | + match ENCODING.to_writer(&mut buf, &self.0) { |
| 121 | + Ok(()) => ( |
| 122 | + [( |
| 123 | + header::CONTENT_TYPE, |
| 124 | + HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()), |
| 125 | + )], |
| 126 | + buf.into_inner().freeze(), |
| 127 | + ) |
| 128 | + .into_response(), |
| 129 | + Err(err) => ( |
| 130 | + StatusCode::INTERNAL_SERVER_ERROR, |
| 131 | + [( |
| 132 | + header::CONTENT_TYPE, |
| 133 | + HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()), |
| 134 | + )], |
| 135 | + err.to_string(), |
| 136 | + ) |
| 137 | + .into_response(), |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +impl<T> Json<T> |
| 143 | +where |
| 144 | + T: DecodeOwned<Text>, |
| 145 | +{ |
| 146 | + fn from_bytes(bytes: &[u8]) -> Result<Self, JsonRejection> { |
| 147 | + let alloc = musli::allocator::System::new(); |
| 148 | + let cx = musli::context::SystemContext::new(&alloc); |
| 149 | + |
| 150 | + if let Ok(value) = ENCODING.from_slice_with(&cx, bytes) { |
| 151 | + return Ok(Json(value)); |
| 152 | + } |
| 153 | + |
| 154 | + let report = cx.report(); |
| 155 | + let report = report.to_string(); |
| 156 | + Err(JsonRejection::Report(report)) |
| 157 | + } |
| 158 | +} |
0 commit comments