main.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. use actix_web::{HttpServer, web, middleware, App};
  2. use actix_cors::Cors;
  3. use sqlx::PgPool;
  4. use crate::app_error::AppError;
  5. mod app_error;
  6. mod routes;
  7. mod controllers;
  8. mod models;
  9. mod logic;
  10. mod auth;
  11. #[actix_web::main]
  12. async fn main() -> Result<(), AppError> {
  13. let app_env = std::env::var("APP_ENV").unwrap_or_else(|_| "development".to_string());
  14. let pool = PgPool::connect("postgres://leemorgan:password123@localhost:5432/homo")
  15. .await
  16. .expect("Failed to start Postgres");
  17. HttpServer::new(move || {
  18. let cors = if app_env == "development" {
  19. Cors::permissive()
  20. } else {
  21. Cors::default()
  22. .allowed_origin_fn(|origin, _req| {
  23. origin.as_bytes().ends_with(b".example.com")
  24. })
  25. .allowed_methods(vec!["GET", "POST", "PUT", "PATCH", "DELETE"])
  26. .allow_any_header()
  27. .supports_credentials()
  28. };
  29. App::new()
  30. .wrap(middleware::Compress::default())
  31. .wrap(cors)
  32. .app_data(web::Data::new(pool.clone()))
  33. .app_data(
  34. web::JsonConfig::default().error_handler(|err, _req| {
  35. AppError::JsonDeserializationError(err.to_string()).into()
  36. })
  37. )
  38. .configure(routes::user::config)
  39. .configure(routes::home::config)
  40. .configure(routes::device::config)
  41. })
  42. .bind(("0.0.0.0", 8000))
  43. .expect("Failed to bind to port")
  44. .run()
  45. .await
  46. .expect("Failed to start server");
  47. Ok(())
  48. }