init
This commit is contained in:
75
backend/src/main.rs
Normal file
75
backend/src/main.rs
Normal file
@ -0,0 +1,75 @@
|
||||
mod db;
|
||||
mod response;
|
||||
mod error;
|
||||
pub mod middlewares;
|
||||
pub mod models;
|
||||
pub mod services;
|
||||
pub mod routes;
|
||||
pub mod utils;
|
||||
|
||||
use axum::Router;
|
||||
use axum::http::{HeaderValue, Method};
|
||||
use tower_http::cors::{CorsLayer, Any, AllowOrigin};
|
||||
use migration::MigratorTrait;
|
||||
use axum::middleware;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
dotenvy::dotenv().ok();
|
||||
tracing_subscriber::fmt().with_env_filter(tracing_subscriber::EnvFilter::from_default_env()).init();
|
||||
|
||||
let db = db::init_db().await?;
|
||||
|
||||
// run migrations
|
||||
migration::Migrator::up(&db, None).await.expect("migration up");
|
||||
|
||||
let allow_origins = std::env::var("CORS_ALLOW_ORIGINS").unwrap_or_else(|_| "http://localhost:5173".into());
|
||||
let origin_values: Vec<HeaderValue> = allow_origins
|
||||
.split(',')
|
||||
.filter_map(|s| HeaderValue::from_str(s.trim()).ok())
|
||||
.collect();
|
||||
|
||||
let allowed_methods = [
|
||||
Method::GET,
|
||||
Method::POST,
|
||||
Method::PUT,
|
||||
Method::PATCH,
|
||||
Method::DELETE,
|
||||
Method::OPTIONS,
|
||||
];
|
||||
|
||||
let cors = if origin_values.is_empty() {
|
||||
// 当允许任意来源时,不能与 allow_credentials(true) 同时使用
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(allowed_methods.clone())
|
||||
.allow_headers([
|
||||
axum::http::header::ACCEPT,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::header::AUTHORIZATION,
|
||||
])
|
||||
.allow_credentials(false)
|
||||
} else {
|
||||
CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(origin_values))
|
||||
.allow_methods(allowed_methods)
|
||||
.allow_headers([
|
||||
axum::http::header::ACCEPT,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::header::AUTHORIZATION,
|
||||
])
|
||||
.allow_credentials(true)
|
||||
};
|
||||
|
||||
let api = routes::api_router().with_state(db.clone());
|
||||
|
||||
let app = Router::new()
|
||||
.nest("/api", api)
|
||||
.layer(cors)
|
||||
.layer(middleware::from_fn_with_state(db.clone(), middlewares::logging::request_logger));
|
||||
|
||||
let addr = format!("{}:{}", std::env::var("APP_HOST").unwrap_or("0.0.0.0".into()), std::env::var("APP_PORT").unwrap_or("8080".into()));
|
||||
tracing::info!("listening on {}", addr);
|
||||
axum::serve(tokio::net::TcpListener::bind(addr).await?, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user