main.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
  2. use serde_json::json;
  3. use sqlx::PgPool;
  4. use std::env;
  5. pub mod auth;
  6. mod models;
  7. mod routes;
  8. pub struct Config {
  9. pub jwt_secret: String,
  10. pub is_production: bool,
  11. }
  12. #[get("/")]
  13. async fn index() -> impl Responder {
  14. "Welcome to the Torus API"
  15. }
  16. #[actix_web::main]
  17. async fn main() -> std::io::Result<()> {
  18. dotenvy::dotenv().ok();
  19. let app_env = env::var("APP_ENV").unwrap_or_else(|_| "development".to_string());
  20. let port: u16 = env::var("PORT")
  21. .unwrap_or_else(|_| "8080".to_string())
  22. .parse()
  23. .expect("PORT must be a valid number");
  24. let host = if app_env == "production" {
  25. "example.com".to_string()
  26. } else {
  27. "127.0.0.1".to_string()
  28. };
  29. let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
  30. let pool = PgPool::connect(&database_url)
  31. .await
  32. .expect("Failed to connect to Postgres");
  33. let config = web::Data::new(Config {
  34. jwt_secret: env::var("JWT_SECRET").expect("JWT_SECRET must be set"),
  35. is_production: app_env == "production",
  36. });
  37. println!("Starting server on {}:{} ({})", host, port, app_env);
  38. HttpServer::new(move || {
  39. let json_cfg = web::JsonConfig::default().error_handler(|_err, _req| {
  40. let response = HttpResponse::BadRequest()
  41. .json(json!({"error": "Invalid request body. Please check your data and try again."}));
  42. actix_web::error::InternalError::from_response(_err, response).into()
  43. });
  44. App::new()
  45. .app_data(web::Data::new(pool.clone()))
  46. .app_data(config.clone())
  47. .app_data(json_cfg)
  48. .service(index)
  49. .service(routes::users::create::create_user)
  50. .service(routes::users::login::login)
  51. .service(routes::users::logout::logout)
  52. .service(routes::users::get::get_user)
  53. .service(routes::workouts::create::create_workout)
  54. .service(routes::workouts::delete::delete_workout)
  55. .service(routes::workouts::get::get_workout)
  56. .service(routes::workouts::list::list_workouts)
  57. .service(routes::workouts::update::update_workout)
  58. })
  59. .bind((host.as_str(), port))?
  60. .run()
  61. .await
  62. }