|
| 1 | +static JSON_MIME: &str = "application/json"; |
| 2 | +pub(in crate::server) static JSON_HEADER_VAL: HeaderValue = HeaderValue::from_static(JSON_MIME); |
| 3 | + |
| 4 | +use hyper::{ |
| 5 | + header::{self, HeaderValue}, |
| 6 | + Body, StatusCode, |
| 7 | +}; |
| 8 | +pub(crate) fn json_error_rsp( |
| 9 | + error: impl ToString, |
| 10 | + status: http::StatusCode, |
| 11 | +) -> http::Response<Body> { |
| 12 | + mk_rsp( |
| 13 | + status, |
| 14 | + &serde_json::json!({ |
| 15 | + "error": error.to_string(), |
| 16 | + "status": status.as_u16(), |
| 17 | + }), |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +pub(crate) fn json_rsp(val: &impl serde::Serialize) -> http::Response<Body> { |
| 22 | + mk_rsp(StatusCode::OK, val) |
| 23 | +} |
| 24 | + |
| 25 | +pub(crate) fn accepts_json<B>(req: &http::Request<B>) -> Result<(), http::Response<Body>> { |
| 26 | + if let Some(accept) = req.headers().get(header::ACCEPT) { |
| 27 | + let accept = match std::str::from_utf8(accept.as_bytes()) { |
| 28 | + Ok(accept) => accept, |
| 29 | + Err(_) => { |
| 30 | + tracing::warn!("Accept header is not valid UTF-8"); |
| 31 | + return Err(json_error_rsp( |
| 32 | + "Accept header must be UTF-8", |
| 33 | + StatusCode::BAD_REQUEST, |
| 34 | + )); |
| 35 | + } |
| 36 | + }; |
| 37 | + let will_accept_json = accept.contains(JSON_MIME) |
| 38 | + || accept.contains("application/*") |
| 39 | + || accept.contains("*/*"); |
| 40 | + if !will_accept_json { |
| 41 | + tracing::warn!(?accept, "Accept header will not accept 'application/json'"); |
| 42 | + return Err(http::Response::builder() |
| 43 | + .status(StatusCode::NOT_ACCEPTABLE) |
| 44 | + .body(JSON_MIME.into()) |
| 45 | + .expect("builder with known status code must not fail")); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + Ok(()) |
| 50 | +} |
| 51 | + |
| 52 | +fn mk_rsp(status: StatusCode, val: &impl serde::Serialize) -> http::Response<Body> { |
| 53 | + match serde_json::to_vec(val) { |
| 54 | + Ok(json) => http::Response::builder() |
| 55 | + .status(status) |
| 56 | + .header(header::CONTENT_TYPE, JSON_HEADER_VAL.clone()) |
| 57 | + .body(json.into()) |
| 58 | + .expect("builder with known status code must not fail"), |
| 59 | + Err(error) => { |
| 60 | + tracing::warn!(?error, "failed to serialize JSON value"); |
| 61 | + http::Response::builder() |
| 62 | + .status(StatusCode::INTERNAL_SERVER_ERROR) |
| 63 | + .body(format!("failed to serialize JSON value: {error}").into()) |
| 64 | + .expect("builder with known status code must not fail") |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments