Code docs

This commit is contained in:
Lucien Greathouse
2021-06-11 22:19:50 -04:00
parent e482d038c6
commit 17fdd18c55
12 changed files with 72 additions and 37 deletions

View File

@@ -2,6 +2,21 @@ use futures::{future, Future};
use hyper::{header::CONTENT_TYPE, Body, Response, StatusCode};
use serde::Serialize;
/// Respond to a request with JSON and the given status code.
pub fn json<T: Serialize>(
value: T,
code: StatusCode,
) -> Box<dyn Future<Item = hyper::Response<hyper::Body>, Error = hyper::Error> + Send> {
Box::new(future::ok(response_json(value, code)))
}
/// Respond to a request with a 200 OK response containing JSON.
pub fn json_ok<T: Serialize>(
value: T,
) -> Box<dyn Future<Item = hyper::Response<hyper::Body>, Error = hyper::Error> + Send> {
json(value, StatusCode::OK)
}
fn response_json<T: Serialize>(value: T, code: StatusCode) -> Response<Body> {
let serialized = match serde_json::to_string(&value) {
Ok(v) => v,
@@ -20,16 +35,3 @@ fn response_json<T: Serialize>(value: T, code: StatusCode) -> Response<Body> {
.body(Body::from(serialized))
.unwrap()
}
pub fn json<T: Serialize>(
value: T,
code: StatusCode,
) -> Box<dyn Future<Item = hyper::Response<hyper::Body>, Error = hyper::Error> + Send> {
Box::new(future::ok(response_json(value, code)))
}
pub fn json_ok<T: Serialize>(
value: T,
) -> Box<dyn Future<Item = hyper::Response<hyper::Body>, Error = hyper::Error> + Send> {
json(value, StatusCode::OK)
}