Skip to main content

apimock_server/response/
status_code_response.rs

1use hyper::{HeaderMap, StatusCode};
2
3use std::collections::HashMap;
4
5use crate::{response_handler::ResponseHandler, types::BoxBody};
6
7/// custom status code response (body is empty)
8///
9/// `headers` are applied last, after the status is set, so an explicit
10/// header always wins over anything `ResponseHandler` would otherwise
11/// infer (RFC 045: an explicitly configured header wins over an
12/// inferred default).
13pub fn status_code_response(
14    status_code: &StatusCode,
15    headers: Option<&HashMap<String, Option<String>>>,
16    request_headers: &HeaderMap,
17) -> Result<hyper::Response<BoxBody>, hyper::http::Error> {
18    let mut response_handler = ResponseHandler::default().with_status(status_code);
19    if let Some(headers) = headers {
20        response_handler = response_handler.with_headers(headers.to_owned());
21    }
22    response_handler.into_response(request_headers)
23}
24
25/// custom status code response with message in body
26///
27/// See [`status_code_response`] for why `headers` is applied after
28/// `with_text` — an explicit `content-type` in `headers` must win over
29/// the `text/plain` default `with_text` sets.
30pub fn status_code_response_with_message(
31    status_code: &StatusCode,
32    message: &str,
33    headers: Option<&HashMap<String, Option<String>>>,
34    request_headers: &HeaderMap,
35) -> Result<hyper::Response<BoxBody>, hyper::http::Error> {
36    let mut response_handler = ResponseHandler::default()
37        .with_status(status_code)
38        .with_text(message, None);
39    if let Some(headers) = headers {
40        response_handler = response_handler.with_headers(headers.to_owned());
41    }
42    response_handler.into_response(request_headers)
43}