From c7112e995b5c1f587b438a9e1cf03f9c011fe81f Mon Sep 17 00:00:00 2001
From: atoav <dh@atoav.com>
Date: Sat, 4 Apr 2020 18:58:46 +0200
Subject: [PATCH] Always return json

---
 src/main.rs | 36 +++++++++++++++++++++++-------------
 1 file changed, 23 insertions(+), 13 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index a3df1bb..0b61964 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -20,7 +20,8 @@
 use crate::form::FormData;
 use crate::email::send_mail;
 use actix_cors::Cors;
-use actix_web::{http::header, error, web, FromRequest, HttpResponse, Responder};
+use serde::Serialize;
+use actix_web::{http::header, error, web, FromRequest, HttpResponse, web::Json};
 use actix_web::middleware::Logger;
 use lazy_static::lazy_static;
 
@@ -37,12 +38,25 @@ type GenResult<T> = Result<T, GenError>;
 
 
 
+#[derive(Serialize)]
+struct Status {
+    status: String,
+}
+
+impl Status {
+    fn into_response<S>(body: S) -> Option<GenResult<Json<Status>>> where S: Into<String> {
+        let body = body.into();
+        Some(Ok(Json(Status{status:body})))
+    }
+}
+
+
 /// The index route deserializes [FormData] from the request's JSON body, whose maximum payload size is defined in the config. The following processing steps are taken:
 /// 1. Check if the identifier provided by the Endpoint is found among the endpoints in the `config.toml`
 /// 2. Check if the length of the files in the FormData is within the provided limits (some of which are hardcoded, some of which are setable via config)
 /// 3. Check if the email is valid
 /// 4. Send the email to the defined target
-async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> impl Responder {
+async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> GenResult<web::Json<Status>> {
     let mut response = None;
 
     println!("Received message");
@@ -53,7 +67,8 @@ async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> impl
                                    .find(|e| e.identifier == data.identifier);
 
     if matching_endpoints.is_none() {
-        response = Some(HttpResponse::NotAcceptable().body(format!("Error: The Endpoint with the identifier-value \"{}\" was not named in the config", data.identifier)))
+        eprintln!("Error: The Endpoint with the identifier-value \"{}\" was not named in the config", data.identifier);
+        response = Status::into_response(format!("Error: unregistered origin"));
     }
 
     // Check length of form data
@@ -61,7 +76,7 @@ async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> impl
         let result = data.check_length(matching_endpoints.unwrap());
 
         match result {
-            Err(ref e) => response = Some(HttpResponse::PayloadTooLarge().body(format!("Error while checking form data: {}", e))),
+            Err(ref e) => response = Status::into_response(format!("Error while checking form data: {}", e)),
             _ => ()
         }
     }
@@ -71,7 +86,7 @@ async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> impl
         let result = data.check_existence(matching_endpoints.unwrap()).await;
 
         match result {
-            Err(ref e) => response = Some(HttpResponse::NotAcceptable().body(format!("Error while checking mail validity: {}", e))),
+            Err(ref e) => response = Status::into_response(format!("Error while checking mail validity: {}", e)),
             Ok(_) => println!("Email is valid")
         }
     }
@@ -80,14 +95,9 @@ async fn index(mut data: web::Json<FormData>, data2: web::Data<Config>) -> impl
         match send_mail(&data, config, matching_endpoints.unwrap()){
             Ok(_) => {
                 println!("Email relayed to target adress");
-                let m = format!("Thank you for your message. I will come back to you soon.");
-                response = Some(HttpResponse::Ok().body(m))
+                response = Status::into_response(format!("success"));
             },
-            Err(e) => {
-
-                let m = format!("Error while sending mail: {}", e);
-                response = Some(HttpResponse::InternalServerError().body(m))
-            }
+            Err(e) => response = Status::into_response(format!("Error while sending mail: {}", e))
         }    
     }
     response.unwrap()
@@ -105,7 +115,7 @@ async fn main() -> std::io::Result<()> {
     println!("Read config from \"{:?}\"", CONFIG.path());
     let ip = &CONFIG.server.ip;
     let port = &CONFIG.server.port;
-    
+
     std::env::set_var("RUST_LOG", "actix_web=info");
     env_logger::init();
 
-- 
GitLab