1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//! HTTP API Server utilities.

use hyper::{header, http, Body, Response, StatusCode};
use serde::Serialize;
use serde_json::to_string as to_json_string;

static NOT_FOUND: &[u8] = b"{\"error\":\"not found\"}";
static INTERNAL_SERVER_ERROR: &[u8] = b"{\"error\":\"server error\"}";

/// Builds a new server response.
pub fn build_response<T: Into<Body>>(s: StatusCode, b: T) -> Result<Response<Body>, http::Error> {
    Response::builder()
        .status(s)
        .header(header::CONTENT_TYPE, "application/json")
        .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
        .body(b.into())
}

/// Builds a new server response with status code OK.
pub fn ok_response<T: Into<Body>>(b: T) -> Result<Response<Body>, http::Error> {
    build_response(StatusCode::OK, b)
}

/// Builds a new server response with status code 404.
pub fn not_found() -> Result<Response<Body>, http::Error> {
    build_response(StatusCode::NOT_FOUND, NOT_FOUND)
}

/// Creates a new server error response with status code 500.
pub fn server_error() -> Result<Response<Body>, http::Error> {
    build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR)
}

/// Builds a new JSON response from serializable.
pub fn json_response<T: Serialize>(data: &T) -> Result<Response<Body>, http::Error> {
    match to_json_string(data) {
        Ok(json) => ok_response(json),
        Err(_) => build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR),
    }
}