feat: #12 start impl router

This commit is contained in:
landrigun 2022-10-06 16:51:51 +00:00
parent 495d57c403
commit df38268566
4 changed files with 47 additions and 6 deletions

View File

@ -1,7 +1,9 @@
//! handlers module includes tools to parse an HTTP request and build and HTTP response
//! http module includes tools to parse an HTTP request and build and HTTP response
pub mod request;
pub mod response;
pub mod router;
pub use request::handle_request;
pub use response::HTTPResponse;
pub use request::{handle_request, HTTPRequest};
pub use response::{HTTPResponse, HTTPStatusCode};
pub use router::ROUTER;

View File

@ -10,7 +10,8 @@ use json;
use crate::stores::FileStore;
use crate::stores::Store;
enum HTTPStatusCode {
#[derive(Debug, PartialEq)]
pub enum HTTPStatusCode {
Http200,
Http400,
Http403,
@ -56,12 +57,16 @@ impl HTTPStatusLine {
fn set_status_code(&mut self, code: HTTPStatusCode) {
self.status_code = code;
}
pub fn get_status_code(&self) -> &HTTPStatusCode {
&self.status_code
}
}
/// represents an HTTP response (headers are not parsed)
/// NOTE: for simplicity, only JSON body are accepted
pub struct HTTPResponse {
status_line: HTTPStatusLine,
pub status_line: HTTPStatusLine,
body: json::JsonValue,
}

34
src/http/router.rs Normal file
View File

@ -0,0 +1,34 @@
//! router aims to handle correctly the request corresponding to the target
use super::{HTTPRequest, HTTPResponse, HTTPStatusCode};
use lazy_static::lazy_static;
// TODO: this must be set in a config file (type might be changed)
const HTTP_TARGETS: &[&'static str; 3] = &["/validate/", "/get/", "/refresh/"];
pub struct Router<'a> {
routes: &'a [&'static str],
}
// assuming a static lifetime
impl Router<'_> {
pub fn route(&self, request_str: &str) -> HTTPResponse {
HTTPResponse::default()
}
}
pub const ROUTER: Router = Router {
routes: HTTP_TARGETS,
};
#[test]
fn test_route() {
let router: &Router = &ROUTER;
let request_str = "POST /get/ HTTP/1.1\r\n\r\n";
let response: HTTPResponse = router.route(request_str);
assert_eq!(
&HTTPStatusCode::Http400,
response.status_line.get_status_code()
);
}

View File

@ -6,7 +6,7 @@ use tokio::{
net::{TcpListener, TcpStream},
};
use http::{handle_request, HTTPResponse};
use http::{handle_request, HTTPResponse, ROUTER};
const SERVER_URL: &str = "127.0.0.1:9000";