Skip to main content

route_util/
make_response.rs

1use http_pool::body::{VariantBody, variant_body};
2use hyper::body::Bytes;
3use hyper::{Response, StatusCode};
4
5/// 文本内容
6pub static TEXT_CONTENT_TYPE: &str = "text/plain; charset=utf-8";
7/// json内容
8pub static JSON_CONTENT_TYPE: &str = "application/json";
9
10pub fn response<B: Into<String>>(
11    code: StatusCode,
12    body: Option<B>,
13    content_type: &str,
14) -> Response<VariantBody> {
15    let builder = Response::builder()
16        .status(code)
17        .header("Content-Type", content_type);
18    if let Some(b) = body {
19        let b = b.into();
20        builder
21            .header("Content-Length", b.len().to_string())
22            .body(variant_body(http_pool::body::Full::new(Bytes::from(b))))
23            .unwrap()
24    } else {
25        builder.body(http_pool::body::empty()).unwrap()
26    }
27}