use std::borrow::Cow;
use bytes::Bytes;
use http::StatusCode;
use http::header::{CONTENT_TYPE, HeaderValue};
use http_body_util::Full;
use serde::Serialize;
pub const CODE_OK: i32 = 200;
#[derive(Debug, Clone)]
pub struct Response<T> {
status: StatusCode,
code: i32,
data: Option<T>,
msg: Cow<'static, str>,
}
pub fn ok<T: Serialize>(data: T) -> Response<T> {
Response {
status: StatusCode::OK,
code: CODE_OK,
data: Some(data),
msg: Cow::Borrowed("success"),
}
}
pub fn ok_msg<T: Serialize>(data: T, msg: impl Into<Cow<'static, str>>) -> Response<T> {
Response {
status: StatusCode::OK,
code: CODE_OK,
data: Some(data),
msg: msg.into(),
}
}
pub fn fail(code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
Response {
status: StatusCode::OK,
code,
data: None,
msg: msg.into(),
}
}
pub fn fail_status(http_status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
Response {
status: sanitize_status(http_status),
code,
data: None,
msg: msg.into(),
}
}
fn sanitize_status(status: u16) -> StatusCode {
if status < 200 {
return StatusCode::INTERNAL_SERVER_ERROR;
}
StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
impl<T> Response<T> {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn code(&self) -> i32 {
self.code
}
pub fn msg(&self) -> &str {
&self.msg
}
pub fn with_status(mut self, http_status: u16) -> Self {
self.status = sanitize_status(http_status);
self
}
}
impl Response<()> {
pub fn erase<T>(self) -> Response<T> {
Response {
status: self.status,
code: self.code,
data: None,
msg: self.msg,
}
}
}
impl<T: Serialize> Response<T> {
pub fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
let data = match &self.data {
Some(d) => serde_json::to_vec(d)?,
None => Vec::new(),
};
let data: &[u8] = if data.is_empty() || data == b"null" {
b"{}"
} else {
&data
};
let msg = serde_json::to_vec(self.msg.as_ref())?;
let mut out = Vec::with_capacity(data.len() + msg.len() + 32);
out.extend_from_slice(b"{\"code\":");
out.extend_from_slice(self.code.to_string().as_bytes());
out.extend_from_slice(b",\"data\":");
out.extend_from_slice(data);
out.extend_from_slice(b",\"msg\":");
out.extend_from_slice(&msg);
out.push(b'}');
Ok(out)
}
pub fn into_http(self) -> http::Response<Full<Bytes>> {
match self.to_json() {
Ok(body) => {
let mut resp = http::Response::new(Full::new(Bytes::from(body)));
*resp.status_mut() = self.status;
resp.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf-8"),
);
resp
}
Err(_) => {
let mut resp = http::Response::new(Full::new(Bytes::from_static(
b"internal error: response marshal failed\n",
)));
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
resp.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
resp
}
}
}
}
#[cfg(feature = "axum")]
impl<T: Serialize> axum::response::IntoResponse for Response<T> {
fn into_response(self) -> axum::response::Response {
self.into_http().map(axum::body::Body::new)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use http_body_util::BodyExt;
use serde::Serialize;
use super::*;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct User {
user_id: String,
nick_name: Option<String>,
}
fn json<T: Serialize>(r: &Response<T>) -> String {
String::from_utf8(r.to_json().unwrap()).unwrap()
}
#[test]
fn normalizes_empty_data() {
assert_eq!(json(&ok(())), r#"{"code":200,"data":{},"msg":"success"}"#);
assert_eq!(json(&ok(None::<User>)), r#"{"code":200,"data":{},"msg":"success"}"#);
assert_eq!(
json(&ok(Vec::<User>::new())),
r#"{"code":200,"data":[],"msg":"success"}"#
);
assert_eq!(
json(&ok(HashMap::<String, i32>::new())),
r#"{"code":200,"data":{},"msg":"success"}"#
);
assert_eq!(
json(&fail(40401, "user not found")),
r#"{"code":40401,"data":{},"msg":"user not found"}"#
);
}
#[test]
fn serializes_data_and_escapes_msg() {
let u = User {
user_id: "u_1".into(),
nick_name: None,
};
assert_eq!(
json(&ok_msg(u, "done \"ok\"")),
r#"{"code":200,"data":{"userId":"u_1","nickName":null},"msg":"done \"ok\""}"#
);
assert_eq!(json(&ok(0)), r#"{"code":200,"data":0,"msg":"success"}"#);
assert_eq!(json(&ok("")), r#"{"code":200,"data":"","msg":"success"}"#);
}
#[test]
fn status_handling() {
assert_eq!(fail(1, "x").status(), StatusCode::OK);
assert_eq!(
fail_status(429, 42900, "too many requests").status(),
StatusCode::TOO_MANY_REQUESTS
);
assert_eq!(fail_status(101, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(fail_status(0, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(fail_status(1000, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(ok(()).with_status(201).status(), StatusCode::CREATED);
let erased: Response<User> = fail(40001, "bad").erase();
assert_eq!((erased.code(), erased.msg()), (40001, "bad"));
}
struct Broken;
impl Serialize for Broken {
fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom("boom"))
}
}
#[tokio::test]
async fn into_http() {
let resp = fail_status(401, 40100, "unauthorized").into_http();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
assert_eq!(resp.headers()[CONTENT_TYPE], "application/json; charset=utf-8");
let body = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], br#"{"code":40100,"data":{},"msg":"unauthorized"}"#);
let resp = ok(Broken).into_http();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}