cxmr_util_servers/
helpers.rs

1//! HTTP API Server utilities.
2
3use 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
10/// Builds a new server response.
11pub 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
19/// Builds a new server response with status code OK.
20pub fn ok_response<T: Into<Body>>(b: T) -> Result<Response<Body>, http::Error> {
21    build_response(StatusCode::OK, b)
22}
23
24/// Builds a new server response with status code 404.
25pub fn not_found() -> Result<Response<Body>, http::Error> {
26    build_response(StatusCode::NOT_FOUND, NOT_FOUND)
27}
28
29/// Creates a new server error response with status code 500.
30pub fn server_error() -> Result<Response<Body>, http::Error> {
31    build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR)
32}
33
34/// Builds a new JSON response from serializable.
35pub 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}