main.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. use actix_web::{App, HttpServer, web};
  2. use std::{sync::OnceLock, env};
  3. use mongodb::{Client, Database};
  4. mod routes;
  5. mod models;
  6. mod controllers;
  7. mod dto;
  8. mod app_error;
  9. mod auth;
  10. pub static HTML: OnceLock<String> = OnceLock::new();
  11. #[actix_web::main]
  12. async fn main() -> std::io::Result<()> {
  13. let node_env = env::var("NODE_ENV").unwrap_or_else(|_| "development".to_string());
  14. let uri = if node_env == "production" {
  15. env::var("MONGO_URI").expect("MONGO_URI must be set in production")
  16. } else {
  17. "mongodb://127.0.0.1:27017".to_string()
  18. };
  19. let db = connect_db(&uri, "suma").await;
  20. let html = std::fs::read_to_string("src/views/build.html")
  21. .expect("Failed to read HTML");
  22. HTML.set(html).expect("Failed to set global HTML");
  23. HttpServer::new(move || {
  24. App::new()
  25. .app_data(web::Data::new(db.clone()))
  26. .configure(routes::other::config)
  27. .configure(routes::user::config)
  28. .configure(routes::account::config)
  29. .configure(routes::transaction::config)
  30. })
  31. .bind(("0.0.0.0", 8000))?
  32. .run()
  33. .await
  34. }
  35. pub async fn connect_db(uri: &str, db_name: &str) -> Database {
  36. let client = Client::with_uri_str(uri).await.expect("Failed to connect to database");
  37. client.database(db_name)
  38. }