apimock_server/response/json_response.rs
1use std::collections::HashMap;
2
3use hyper::{HeaderMap, StatusCode};
4use serde_json::Value;
5
6use crate::{
7 response::error_response::internal_server_error_response, response_handler::ResponseHandler,
8 types::BoxBody,
9};
10
11/// JSON response — used both for `respond.json` (RFC 065, `source` is
12/// `None`) and for a `file_path` pointing at a `.json`/`.json5` file or
13/// a CSV converted to JSON (`source` names the file, for the server
14/// log only — see below).
15///
16/// Parses with the same JSON5 parser `Respond::validate` already
17/// checked this content against at load time (`apimock_routing`'s own
18/// `json5` dependency), so the `_ =>` branch below is unreachable for
19/// `respond.json` and for a `.json`/`.json5` `file_path` in ordinary
20/// operation — both are now validated before the server ever starts
21/// (RFC 065 D3). It stays reachable for CSV→JSON conversion (not
22/// content-validated at load, since the source is CSV, not JSON) and
23/// as a defensive fallback if a file changes on disk after startup.
24///
25/// # Why `source` never reaches the response body (RFC 065 D4)
26///
27/// This used to build the client-facing message as `"{file_path}:
28/// invalid json content"`, putting the server's own filesystem path in
29/// front of every client that hit this branch. The path is still
30/// useful — to whoever runs the server, not to whoever's making the
31/// request — so it goes to the server log via `log::error!` instead;
32/// the client gets a message that names the *problem*, not the
33/// server's directory layout.
34pub fn json_response(
35 json_str: &str,
36 status_code: Option<&StatusCode>,
37 custom_headers: Option<&HashMap<String, Option<String>>>,
38 request_headers: &HeaderMap,
39 source: Option<&str>,
40) -> Result<hyper::Response<BoxBody>, hyper::http::Error> {
41 match json5::from_str::<Value>(json_str) {
42 Ok(content) => {
43 let body = content.to_string();
44 let mut response_handler = ResponseHandler::default().with_json_body(body.as_str());
45 if let Some(status_code) = status_code {
46 response_handler = response_handler.with_status(status_code);
47 }
48 response_handler
49 .with_custom_headers(custom_headers)
50 .into_response(request_headers)
51 }
52 Err(err) => {
53 log::error!(
54 "invalid json content{}: {}",
55 source.map(|s| format!(" ({})", s)).unwrap_or_default(),
56 err
57 );
58 internal_server_error_response("invalid json content", request_headers)
59 }
60 }
61}