1use std::borrow::Cow;
26
27use bytes::Bytes;
28use http::StatusCode;
29use http::header::{CONTENT_TYPE, HeaderValue};
30use http_body_util::Full;
31use serde::Serialize;
32
33pub const CODE_OK: i32 = 200;
35
36#[derive(Debug, Clone)]
38pub struct Response<T> {
39 status: StatusCode,
40 code: i32,
41 data: Option<T>,
42 msg: Cow<'static, str>,
43}
44
45pub fn ok<T: Serialize>(data: T) -> Response<T> {
47 Response {
48 status: StatusCode::OK,
49 code: CODE_OK,
50 data: Some(data),
51 msg: Cow::Borrowed("success"),
52 }
53}
54
55pub fn ok_msg<T: Serialize>(data: T, msg: impl Into<Cow<'static, str>>) -> Response<T> {
57 Response {
58 status: StatusCode::OK,
59 code: CODE_OK,
60 data: Some(data),
61 msg: msg.into(),
62 }
63}
64
65pub fn fail(code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
67 Response {
68 status: StatusCode::OK,
69 code,
70 data: None,
71 msg: msg.into(),
72 }
73}
74
75pub fn fail_status(http_status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
78 Response {
79 status: sanitize_status(http_status),
80 code,
81 data: None,
82 msg: msg.into(),
83 }
84}
85
86fn sanitize_status(status: u16) -> StatusCode {
87 if status < 200 {
88 return StatusCode::INTERNAL_SERVER_ERROR;
89 }
90 StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
91}
92
93impl<T> Response<T> {
94 pub fn status(&self) -> StatusCode {
96 self.status
97 }
98
99 pub fn code(&self) -> i32 {
101 self.code
102 }
103
104 pub fn msg(&self) -> &str {
106 &self.msg
107 }
108
109 pub fn with_status(mut self, http_status: u16) -> Self {
111 self.status = sanitize_status(http_status);
112 self
113 }
114}
115
116impl Response<()> {
117 pub fn erase<T>(self) -> Response<T> {
119 Response {
120 status: self.status,
121 code: self.code,
122 data: None,
123 msg: self.msg,
124 }
125 }
126}
127
128impl<T: Serialize> Response<T> {
129 pub fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
131 let data = match &self.data {
132 Some(d) => serde_json::to_vec(d)?,
133 None => Vec::new(),
134 };
135 let data: &[u8] = if data.is_empty() || data == b"null" {
137 b"{}"
138 } else {
139 &data
140 };
141 let msg = serde_json::to_vec(self.msg.as_ref())?;
142
143 let mut out = Vec::with_capacity(data.len() + msg.len() + 32);
144 out.extend_from_slice(b"{\"code\":");
145 out.extend_from_slice(self.code.to_string().as_bytes());
146 out.extend_from_slice(b",\"data\":");
147 out.extend_from_slice(data);
148 out.extend_from_slice(b",\"msg\":");
149 out.extend_from_slice(&msg);
150 out.push(b'}');
151 Ok(out)
152 }
153
154 pub fn into_http(self) -> http::Response<Full<Bytes>> {
156 match self.to_json() {
157 Ok(body) => {
158 let mut resp = http::Response::new(Full::new(Bytes::from(body)));
159 *resp.status_mut() = self.status;
160 resp.headers_mut().insert(
161 CONTENT_TYPE,
162 HeaderValue::from_static("application/json; charset=utf-8"),
163 );
164 resp
165 }
166 Err(_) => {
167 let mut resp = http::Response::new(Full::new(Bytes::from_static(
168 b"internal error: response marshal failed\n",
169 )));
170 *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
171 resp.headers_mut()
172 .insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
173 resp
174 }
175 }
176 }
177}
178
179#[cfg(feature = "axum")]
180impl<T: Serialize> axum::response::IntoResponse for Response<T> {
181 fn into_response(self) -> axum::response::Response {
182 self.into_http().map(axum::body::Body::new)
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use std::collections::HashMap;
189
190 use http_body_util::BodyExt;
191 use serde::Serialize;
192
193 use super::*;
194
195 #[derive(Serialize)]
196 #[serde(rename_all = "camelCase")]
197 struct User {
198 user_id: String,
199 nick_name: Option<String>,
200 }
201
202 fn json<T: Serialize>(r: &Response<T>) -> String {
203 String::from_utf8(r.to_json().unwrap()).unwrap()
204 }
205
206 #[test]
207 fn normalizes_empty_data() {
208 assert_eq!(json(&ok(())), r#"{"code":200,"data":{},"msg":"success"}"#);
209 assert_eq!(json(&ok(None::<User>)), r#"{"code":200,"data":{},"msg":"success"}"#);
210 assert_eq!(
211 json(&ok(Vec::<User>::new())),
212 r#"{"code":200,"data":[],"msg":"success"}"#
213 );
214 assert_eq!(
215 json(&ok(HashMap::<String, i32>::new())),
216 r#"{"code":200,"data":{},"msg":"success"}"#
217 );
218 assert_eq!(
219 json(&fail(40401, "user not found")),
220 r#"{"code":40401,"data":{},"msg":"user not found"}"#
221 );
222 }
223
224 #[test]
225 fn serializes_data_and_escapes_msg() {
226 let u = User {
227 user_id: "u_1".into(),
228 nick_name: None,
229 };
230 assert_eq!(
231 json(&ok_msg(u, "done \"ok\"")),
232 r#"{"code":200,"data":{"userId":"u_1","nickName":null},"msg":"done \"ok\""}"#
233 );
234 assert_eq!(json(&ok(0)), r#"{"code":200,"data":0,"msg":"success"}"#);
235 assert_eq!(json(&ok("")), r#"{"code":200,"data":"","msg":"success"}"#);
236 }
237
238 #[test]
239 fn status_handling() {
240 assert_eq!(fail(1, "x").status(), StatusCode::OK);
241 assert_eq!(
242 fail_status(429, 42900, "too many requests").status(),
243 StatusCode::TOO_MANY_REQUESTS
244 );
245 assert_eq!(fail_status(101, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
246 assert_eq!(fail_status(0, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
247 assert_eq!(fail_status(1000, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
248 assert_eq!(ok(()).with_status(201).status(), StatusCode::CREATED);
249 let erased: Response<User> = fail(40001, "bad").erase();
250 assert_eq!((erased.code(), erased.msg()), (40001, "bad"));
251 }
252
253 struct Broken;
254 impl Serialize for Broken {
255 fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
256 Err(serde::ser::Error::custom("boom"))
257 }
258 }
259
260 #[tokio::test]
261 async fn into_http() {
262 let resp = fail_status(401, 40100, "unauthorized").into_http();
263 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
264 assert_eq!(resp.headers()[CONTENT_TYPE], "application/json; charset=utf-8");
265 let body = resp.into_body().collect().await.unwrap().to_bytes();
266 assert_eq!(&body[..], br#"{"code":40100,"data":{},"msg":"unauthorized"}"#);
267
268 let resp = ok(Broken).into_http();
269 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
270 }
271}