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
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\"}";
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())
}
pub fn ok_response<T: Into<Body>>(b: T) -> Result<Response<Body>, http::Error> {
build_response(StatusCode::OK, b)
}
pub fn not_found() -> Result<Response<Body>, http::Error> {
build_response(StatusCode::NOT_FOUND, NOT_FOUND)
}
pub fn server_error() -> Result<Response<Body>, http::Error> {
build_response(StatusCode::INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR)
}
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),
}
}