feat: #12 add async block in handlers (more readable) + fix tests

This commit is contained in:
2022-10-10 14:59:29 +00:00
parent 53b5c7a65f
commit 71e3db0857
4 changed files with 45 additions and 23 deletions
+1 -2
View File
@@ -1,6 +1,5 @@
//! response handles the incoming request parsed `HTTPRequest`
//! it will check if the `HTTPRequest` is valid and build an HTTPResponse corresponding to the HTTP
//! message specs. see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
//! it will build an HTTPResponse corresponding to the HTTP message specs. see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
//! NOTE: only few parts of the specification has been implemented
use crate::http::request::HTTPVersion;
+34 -14
View File
@@ -12,28 +12,48 @@ use std::pin::Pin;
type FuturePinned<HTTPResponse> = Pin<Box<dyn Future<Output = HTTPResponse>>>;
type Handler = fn(HTTPRequest) -> FuturePinned<HTTPResponse>;
async fn handle_get(request: HTTPRequest) -> HTTPResponse {
// TODO: path to `store.txt` must not be hardcoded, should be in a config file and load at runtime
let mut store = FileStore::new("tests/data/store.txt".to_string());
match request.body {
Some(ref b) => {
let is_auth = store.is_auth(&b.get_data()).await;
if !is_auth {
return HTTPResponse::as_403();
fn handle_get(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
Box::pin(async move {
// TODO: path to `store.txt` must not be hardcoded, should be in a config file and load at runtime
let mut store = FileStore::new("tests/data/store.txt".to_string());
match &request.body {
Some(ref b) => {
let is_auth = store.is_auth(&b.get_data()).await;
if !is_auth {
return HTTPResponse::as_403();
}
HTTPResponse::as_200()
}
HTTPResponse::as_200()
None => HTTPResponse::as_400(),
}
None => HTTPResponse::as_400(),
}
})
}
fn handle_get_pinned(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
Box::pin(handle_get(request))
/// validates the token by checking:
/// * expiration time
fn handle_validate(request: HTTPRequest) -> FuturePinned<HTTPResponse> {
Box::pin(async move {
match &request.body {
Some(ref _b) => {
// TODO: impl the JWT validation
HTTPResponse::as_200()
}
None => HTTPResponse::as_400(),
}
})
}
lazy_static! {
/// defines the map between the URL and its associated callback
/// each authorized targets must implement a function returning `FuturePinned<HTTPResponse>`
// TODO: a macro should be implemented to mask the implementation details
static ref HTTP_METHODS: HashMap<&'static str, Handler> =
HashMap::from([("/get/", handle_get_pinned as Handler),]);
HashMap::from(
[
("/get/", handle_get as Handler),
("/validate/", handle_validate as Handler)
]
);
}
pub struct Router;