meta_srv/service/admin/
util.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use serde::Serialize;
18use snafu::ResultExt;
19use tonic::codegen::http;
20
21use crate::error::{self, Result};
22
23/// Returns a 200 response with a text body.
24pub fn to_text_response(text: &str) -> Result<http::Response<String>> {
25    http::Response::builder()
26        .header("Content-Type", "text/plain")
27        .status(http::StatusCode::OK)
28        .body(text.to_string())
29        .context(error::InvalidHttpBodySnafu)
30}
31
32/// Returns a 200 response with a JSON body.
33pub fn to_json_response<T>(response: T) -> Result<http::Response<String>>
34where
35    T: Serialize + Debug,
36{
37    let response = serde_json::to_string(&response).context(error::SerializeToJsonSnafu {
38        input: format!("{response:?}"),
39    })?;
40    http::Response::builder()
41        .header("Content-Type", "application/json")
42        .status(http::StatusCode::OK)
43        .body(response)
44        .context(error::InvalidHttpBodySnafu)
45}
46
47/// Returns a 404 response with an empty body.
48pub fn to_not_found_response() -> Result<http::Response<String>> {
49    http::Response::builder()
50        .status(http::StatusCode::NOT_FOUND)
51        .body("".to_string())
52        .context(error::InvalidHttpBodySnafu)
53}