apimock_server/
respond_response.rs1use apimock_routing::{ParsedRequest, Respond};
12use console::style;
13use std::path::Path;
14
15use crate::{
16 http_util::delay_response,
17 respond_util::full_file_path,
18 response::{
19 error_response::internal_server_error_response,
20 file_response::FileResponse,
21 json_response::json_response,
22 status_code_response::{status_code_response, status_code_response_with_message},
23 text_response::text_response,
24 },
25 types::BoxBody,
26};
27
28pub async fn respond_response(
53 respond: &Respond,
54 dir_prefix: &str,
55 parsed_request: &ParsedRequest,
56 rule_set_default_delay_ms: Option<u32>,
57 confine_to: Option<&Path>,
58 cors_allow_credentials_origins: &[String],
59) -> Result<hyper::Response<BoxBody>, hyper::http::Error> {
60 if let Some(delay_ms) = respond
61 .delay_response_milliseconds
62 .or(rule_set_default_delay_ms)
63 {
64 delay_response(delay_ms).await;
65 }
66
67 let request_headers = &parsed_request.component_parts.headers;
68
69 if let Some(file_path) = respond.file_path.as_ref() {
71 let Some(full_file_path) = full_file_path(file_path.as_str(), dir_prefix) else {
72 log::error!(
73 "{}:\n{} (prefix = {})",
74 style("file not found").red(),
75 file_path,
76 dir_prefix,
77 );
78 return internal_server_error_response(
79 "failed to get response file",
80 request_headers,
81 cors_allow_credentials_origins,
82 );
83 };
84
85 return FileResponse::new_with_csv_records_jsonpath(
86 full_file_path.as_str(),
87 respond.headers.as_ref(),
88 respond.csv_records_key.clone(),
89 request_headers,
90 confine_to,
91 cors_allow_credentials_origins,
92 )
93 .file_content_response()
94 .await;
95 }
96
97 if let Some(text) = respond.text.as_ref() {
98 return match respond.status_code.as_ref() {
99 Some(status_code) => status_code_response_with_message(
100 status_code,
101 text.as_str(),
102 respond.headers.as_ref(),
103 request_headers,
104 cors_allow_credentials_origins,
105 ),
106 None => text_response(
107 text.as_str(),
108 None,
109 respond.headers.as_ref(),
110 request_headers,
111 cors_allow_credentials_origins,
112 ),
113 };
114 }
115
116 if let Some(json_str) = respond.json.as_ref() {
117 return json_response(
118 json_str.as_str(),
119 respond.status_code.as_ref(),
120 respond.headers.as_ref(),
121 request_headers,
122 None,
123 cors_allow_credentials_origins,
124 );
125 }
126
127 if let Some(status_code) = respond.status_code.as_ref() {
128 return status_code_response(
129 status_code,
130 respond.headers.as_ref(),
131 request_headers,
132 cors_allow_credentials_origins,
133 );
134 }
135
136 internal_server_error_response(
137 "invalid respond def",
138 request_headers,
139 cors_allow_credentials_origins,
140 )
141}