summaryrefslogtreecommitdiff
path: root/server/src/main.rs
blob: 3436e2c716581911166275f54b4738e160970a60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
mod db;
mod errors;
mod logger;
mod models;
mod routes;

use axum::{
    http::{header, Request},
    Router,
};
use std::time::Duration;
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
use tracing::Span;

#[tokio::main]
async fn main() {
    let app = create_app().await;

    let addr: String =
        std::env::var("ALLOWED_HOST").unwrap_or_else(|_| "localhost:3000".to_string());
    tracing::info!("Listening on {}", addr);

    axum::Server::bind(&"127.0.0.1:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn create_app() -> Router {
    logger::setup();
    let _ = db::setup().await;

    let api_routes = Router::new()
        .nest("/users", routes::user::create_route())
        .nest("/auth", routes::auth::create_route());

    Router::new()
        .nest("/v1", api_routes)
        // Mark the `Authorization` request header as sensitive so it doesn't
        // show in logs.
        .layer(SetSensitiveHeadersLayer::new(std::iter::once(
            header::AUTHORIZATION,
        )))
        .layer(
            TraceLayer::new_for_http()
                .on_request(|request: &Request<_>, _span: &Span| {
                    tracing::info!("{} {}", request.method(), request.uri());
                })
                .on_failure(
                    |error: ServerErrorsFailureClass, latency: Duration, _span: &Span| {
                        tracing::error!("{} | {} s", error, latency.as_secs());
                    },
                ),
        )
}