rest/http/
response.rs

1use http::{Response, StatusCode};
2use hyper::Body;
3use serde::Serialize;
4
5/// 200 OK with custom body.
6pub fn ok(body: impl Into<Body>) -> Response<Body> {
7    Response::builder()
8        .status(StatusCode::OK)
9        .body(body.into())
10        .unwrap()
11}
12
13/// 200 OK with JSON body.
14pub fn ok_json<T: Serialize>(val: &T) -> anyhow::Result<Response<Body>> {
15    let body = serde_json::to_vec(val)?;
16    Ok(Response::builder()
17        .status(StatusCode::OK)
18        .header(http::header::CONTENT_TYPE, "application/json")
19        .body(Body::from(body))
20        .unwrap())
21}
22
23/// 400 Bad Request with text body.
24pub fn bad_request(msg: impl Into<Body>) -> Response<Body> {
25    Response::builder()
26        .status(StatusCode::BAD_REQUEST)
27        .body(msg.into())
28        .unwrap()
29}
30
31/// Error response with custom status and message.
32pub fn error(status: StatusCode, msg: impl Into<Body>) -> Response<Body> {
33    Response::builder().status(status).body(msg.into()).unwrap()
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn ok_should_set_status() {
42        let resp = ok("hi");
43        assert_eq!(resp.status(), StatusCode::OK);
44    }
45
46    #[test]
47    fn ok_json_should_serialize() {
48        let resp = ok_json(&serde_json::json!({"a":1})).unwrap();
49        assert_eq!(resp.status(), StatusCode::OK);
50        assert_eq!(
51            resp.headers().get(http::header::CONTENT_TYPE).unwrap(),
52            "application/json"
53        );
54    }
55
56    #[test]
57    fn bad_request_should_set_400() {
58        let resp = bad_request("oops");
59        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
60    }
61
62    #[test]
63    fn error_should_set_status() {
64        let resp = error(StatusCode::UNAUTHORIZED, "nope");
65        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
66    }
67}