zero2prod_axum/src/main.rs

87 lines
2.3 KiB
Rust
Raw Normal View History

2023-07-01 20:34:21 +02:00
#![allow(unused)]
2023-10-07 22:14:22 +02:00
use crate::model::ModelController;
2023-07-01 20:34:21 +02:00
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;
2023-07-02 13:25:54 +02:00
use tower_cookies::CookieManagerLayer;
2023-07-01 20:34:21 +02:00
mod error;
mod web;
2023-10-05 14:33:12 +02:00
mod model;
2023-07-01 20:34:21 +02:00
#[derive(Debug, Deserialize)]
struct HelloParams {
name: Option<String>,
}
#[tokio::main]
2023-10-07 22:14:22 +02:00
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));
2023-07-01 20:34:21 +02:00
let routes_all = Router::new()
.merge(routes_hello())
.merge(web::routes_login::routes())
2023-10-07 22:14:22 +02:00
.nest("/api", routes_apis)
2023-07-01 20:44:48 +02:00
.layer(middleware::map_response(main_response_mapper))
2023-10-05 14:33:12 +02:00
.layer(CookieManagerLayer::new()) // must be above? the auth routes
// TODO: continue video at 22:15
2023-07-01 20:34:21 +02:00
.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();
2023-10-07 22:14:22 +02:00
Ok(())
2023-07-01 20:34:21 +02:00
}
2023-10-05 14:33:12 +02:00
/// Map the response to add headers, etc.
///
/// * `res`: the response to map
2023-07-01 20:44:48 +02:00
async fn main_response_mapper(res: Response) -> Response {
println!("->> {:<12} - main_response_mapper", "HANDLER");
println!();
res
}
2023-10-05 14:33:12 +02:00
/// Serve static files
2023-07-01 20:34:21 +02:00
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>!"))
}