zero2prod_axum/src/main.rs
2023-10-15 22:30:01 +02:00

87 lines
2.4 KiB
Rust

#![allow(unused)]
use crate::model::ModelController;
pub use self::error::{Error, Result};
use std::net::SocketAddr;
use axum::extract::{Path, Query};
use axum::http::{Method, Uri};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, get_service};
use axum::{middleware, Json, Router};
use axum::Server;
use serde::Deserialize;
use tower_http::services::ServeDir;
use tower_cookies::CookieManagerLayer;
mod ctx;
mod error;
mod web;
mod model;
#[derive(Debug, Deserialize)]
struct HelloParams {
name: Option<String>,
}
#[tokio::main]
async fn main() -> Result<()>{
let mc = ModelController::new().await?;
let routes_apis = web::routes_properties::routes(mc.clone()).route_layer(middleware::from_fn(web::mw_auth::mw_require_auth));
let routes_all = Router::new()
.merge(routes_hello())
.merge(web::routes_login::routes())
.nest("/api", routes_apis)
.layer(middleware::map_response(main_response_mapper))
.layer(middleware::from_fn_with_state(mc.clone(), web::mw_auth::mw_ctx_resolver))
.layer(CookieManagerLayer::new()) // must be above? the auth routes
// TODO: continue video at 22:15
.fallback_service(routes_static());
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("->> Listening on {addr}\n");
Server::bind(&addr)
.serve(routes_all.into_make_service())
.await
.unwrap();
Ok(())
}
/// Map the response to add headers, etc.
///
/// * `res`: the response to map
async fn main_response_mapper(res: Response) -> Response {
println!("->> {:<12} - main_response_mapper", "HANDLER");
println!();
res
}
/// Serve static files
fn routes_static() -> Router {
Router::new().nest_service("/", get_service(ServeDir::new("./")))
}
fn routes_hello() -> Router {
Router::new().route("/hello", get(handler_hello))
.route("/hello2/:name", get(handler_hello2))
}
// e.g. `hello?name=jen`
async fn handler_hello(Query(params): Query<HelloParams>) -> impl IntoResponse {
println!("->> {:<12} - handler_hello - {params:?}", "HANDLER");
let name = params.name.as_deref().unwrap_or("World!");
Html(format!("Hello <strong>{name}</strong>!"))
}
// e.g. `hello/jen`
async fn handler_hello2(Path(name): Path<String>) -> impl IntoResponse {
println!("->> {:<12} - handler_hello_path - {name:?}", "HANDLER");
Html(format!("Hello <strong>{name}</strong>!"))
}