actix_json_response/
lib.rs1pub struct JsonResponse<T: serde::Serialize> {
2 pub value: T,
3 pub status_code: Option<actix_web::http::StatusCode>,
4}
5
6impl<T: serde::Serialize> From<T> for JsonResponse<T> {
7 fn from(value: T) -> Self {
8 Self {
9 value,
10 status_code: None,
11 }
12 }
13}
14
15impl<T: serde::Serialize> JsonResponse<T> {
16 pub fn with_status_code(mut self, status_code: actix_web::http::StatusCode) -> Self {
17 self.status_code = Some(status_code);
18
19 self
20 }
21}
22
23impl<T: serde::Serialize> actix_web::Responder for JsonResponse<T> {
24 type Body = actix_web::body::BoxBody;
25
26 fn respond_to(self, _: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
27 match serde_json::to_string(&self.value) {
28 Err(err) => actix_web::HttpResponse::from_error(err),
29 Ok(value) => actix_web::HttpResponseBuilder::new(
30 self.status_code.unwrap_or(actix_web::http::StatusCode::OK),
31 )
32 .content_type("application/json")
33 .body(value),
34 }
35 }
36}