1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2024-11-23 22:09:22 +00:00
comunicapiv3/src/controllers/server.rs

80 lines
2.2 KiB
Rust
Raw Normal View History

2020-05-21 13:28:07 +00:00
use actix_web::{App, HttpResponse, HttpServer, web, http};
use crate::controllers::routes::{get_routes, Route};
use crate::data::config::Config;
use crate::data::http_error::HttpError;
use crate::controllers::routes::Method::{GET, POST};
use crate::data::http_request_handler::HttpRequestHandler;
/// Main server functions
///
/// @author Pierre Hubert
/// Process an incoming request
async fn process_request(req: web::HttpRequest) -> HttpResponse {
let routes = get_routes();
// We search the appropriate route for the request
let mut route: Option<&Route> = None;
for el in &routes {
// Check verb
if !(req.method() == http::Method::GET && el.method == GET) &&
!(req.method() == http::Method::POST && el.method == POST) {
continue;
}
// Check path
if !el.uri.eq(req.uri()) {
continue;
}
route = Some(el);
break;
}
// Check if a route was found
if let None = route {
return HttpResponse::NotFound().json(HttpError::not_found("Method not found!"));
}
let route = route.unwrap();
// Execute the request
let mut request = HttpRequestHandler::new(req);
match (route.func)(&mut request) {
// Set default error response if required
Err(e) => {
if !request.has_response() {
request.internal_error(e).unwrap_err();
}
}
// Set default success response if required
Ok(_) => {
if !request.has_response() {
request.success("Success").unwrap()
}
}
// I use this to be quiet with IntelliJ
#[allow(unreachable_patterns)]
_ => {println!("Unexpected case (server.rs)!")}
}
request.response()
}
/// Given the configuration, start the server
pub async fn start_server(conf: &Config) -> std::io::Result<()> {
let addr = conf.server_listen_address();
println!("Start to listen on http://{}/", addr);
HttpServer::new(|| {
App::new()
.route("**", web::get().to(process_request))
.route("**", web::post().to(process_request))
}).bind(&addr)?.run().await
}