Skip to main content

mini_serve/
response.rs

1use hyper::{Response, StatusCode};
2use http_body_util::combinators::BoxBody;
3use http_body_util::Full;
4use hyper::body::Bytes;
5use serde::Serialize;
6
7use crate::error::ServeError;
8use crate::handler::ResponseBody;
9
10/// Build a JSON response with the given status code and serializable value.
11///
12/// Sets `Content-Type: application/json` and `Content-Length` headers.
13/// Returns `500 Internal Server Error` if serialization fails.
14pub fn json<T: Serialize>(status: StatusCode, value: &T) -> Result<Response<ResponseBody>, ServeError> {
15	let body = serde_json::to_string(value)
16		.map_err(|_| ServeError::new(500, "failed to serialize response"))?;
17	let len = body.len();
18	Response::builder()
19		.status(status)
20		.header("content-type", "application/json")
21		.header("content-length", len)
22		.body(BoxBody::new(Full::new(Bytes::from(body))))
23		.map_err(|_| ServeError::new(500, "failed to build response"))
24}