cxmr_util_servers/
helpers.rs1use hyper::{header, http, Body, Response, StatusCode};
4use serde::Serialize;
5use serde_json::to_string as to_json_string;
6
7static NOT_FOUND: &[u8] = b"{\"error\":\"not found\"}";
8static INTERNAL_SERVER_ERROR: &[u8] = b"{\"error\":\"server error\"}";
9
10pub fn build_response<T: Into<Body>>(s: StatusCode, b: T) -> Result<Response<Body>, http::Error> {
12 Response::builder()
13 .status(s)
14 .header(header::CONTENT_TYPE, "application/json")
15 .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
16 .body(b.into())
17}
18
19pub fn ok_response<T: Into<Body>>(b: T) -> Result<Response<Body>, http::Error> {
21 build_response(StatusCode::OK, b)
22}
23
24pub fn not_found() -> Result<Response<Body>, http::Error> {
26 build_response(StatusCode::NOT_FOUND, NOT_FOUND)
27}
28
29pub fn server_error() -> Result<Response<Body>, http::Error> {
31 build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR)
32}
33
34pub fn json_response<T: Serialize>(data: &T) -> Result<Response<Body>, http::Error> {
36 match to_json_string(data) {
37 Ok(json) => ok_response(json),
38 Err(_) => build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR),
39 }
40}