main.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #![feature(custom_attribute)]
  2. #![feature(custom_derive, plugin)]
  3. #![feature(optin_builtin_traits)]
  4. #![feature(proc_macro)]
  5. #![feature(core_intrinsics)]
  6. mod sql;
  7. mod base;
  8. mod user;
  9. mod db;
  10. mod cache;
  11. mod product;
  12. mod session;
  13. mod echo;
  14. mod image;
  15. mod price;
  16. mod appointment;
  17. #[macro_use]
  18. extern crate serde_derive;
  19. extern crate iron;
  20. extern crate staticfile;
  21. extern crate router;
  22. extern crate bodyparser;
  23. extern crate persistent;
  24. extern crate r2d2;
  25. extern crate r2d2_postgres;
  26. extern crate r2d2_redis;
  27. extern crate redis;
  28. extern crate serde;
  29. extern crate serde_json;
  30. extern crate uuid;
  31. extern crate futures;
  32. use std::ops::Deref;
  33. use futures::Future;
  34. use redis::Commands;
  35. use r2d2_redis::RedisConnectionManager;
  36. use uuid::Uuid;
  37. use serde::{Deserialize, Deserializer};
  38. use std::default::Default;
  39. use std::thread;
  40. use std::sync::Arc;
  41. use std::sync::RwLock;
  42. use router::Router;
  43. use mount::Mount;
  44. use staticfile::Static;
  45. use std::path::Path;
  46. use std::fs::File;
  47. use std::env;
  48. use persistent::{Read, Write};
  49. use iron::prelude::*;
  50. use iron::status;
  51. use iron::typemap::Key;
  52. use iron::AfterMiddleware;
  53. extern crate mount;
  54. struct App {
  55. name: String,
  56. version: String,
  57. }
  58. impl App {
  59. pub fn new(name: String) -> App {
  60. let version: String = match env::var("APP_VERSION") {
  61. Ok(val) => val,
  62. Err(_) => "0.0.0".to_string(),
  63. };
  64. App {
  65. name: name,
  66. version: version,
  67. }
  68. }
  69. pub fn info(&self) -> String {
  70. return self.name.to_string() + " | " + &self.version;
  71. }
  72. }
  73. struct Location {
  74. latitude: f64,
  75. longitude: f64,
  76. timestamp: f64,
  77. }
  78. fn reset(req: &mut Request) -> IronResult<Response> {
  79. let pool = req.get::<Read<db::AppDb>>().unwrap();
  80. let conn = pool.get().unwrap();
  81. conn.query(sql::SQL_RESET, &[]);
  82. Ok(Response::with((status::Ok, "DB-RESET")))
  83. }
  84. fn root(req: &mut Request, app: App) -> IronResult<Response> {
  85. match req.url.path()[0] {
  86. "health" => return health(req),
  87. "reset" => return reset(req),
  88. _ => return Ok(Response::with((status::Ok, app.info()))),
  89. }
  90. }
  91. fn health(req: &mut Request) -> IronResult<Response> {
  92. Ok(Response::with((status::Ok, "Alive and kickin it")))
  93. }
  94. fn get_router() -> fn(&mut Request) -> IronResult<Response> {
  95. fn router(req: &mut Request) -> IronResult<Response> {
  96. println!("{:?}", req.url.path());
  97. let app = App::new("!HairParty!".to_string());
  98. match base::url_fmt(req.method.as_ref(), req.url.path()[0]).as_str() {
  99. "post_product" => return product::put(req),
  100. "get_product" => return product::get(req),
  101. "get_products" => return product::get_all(req),
  102. "post_session" => return session::put(req),
  103. "get_session" => return session::get(req),
  104. "get_sessions" => return session::get_all(req),
  105. "post_appointment" => return appointment::put(req),
  106. "get_appointment" => return appointment::get(req),
  107. "get_appointments" => return appointment::get_all(req),
  108. "post_price" => return price::put(req),
  109. "get_price" => return price::get(req),
  110. "get_prices" => return price::get_all(req),
  111. "post_image" => return image::put(req),
  112. "get_image" => return image::get(req),
  113. "get_images" => return image::get_all(req),
  114. "post_user" => return user::put(req),
  115. "get_user" => return user::get(req),
  116. "get_users" => return user::get_all(req),
  117. "post_login" => return user::login(req),
  118. "echo" => return echo::echo(req),
  119. _ => return root(req, app),
  120. }
  121. }
  122. return router;
  123. }
  124. const MAX_BODY_LENGTH: usize = 1024 * 1024 * 10;
  125. struct CorsMiddleware;
  126. impl AfterMiddleware for CorsMiddleware {
  127. fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response> {
  128. let _ = res.headers.set_raw("access-control-allow-origin".to_string(),
  129. vec![b"*".to_vec()]);
  130. if req.method == iron::method::Method::Options {
  131. let _ = res.headers.set_raw("access-control-allow-headers".to_string(),
  132. vec![b"accept, content-type".to_vec()]);
  133. let _ = res.headers.set_raw("access-control-allow-methods".to_string(),
  134. vec![b"GET,POST,DELETE,OPTIONS,PATCH".to_vec()]);
  135. }
  136. res.headers.set(iron::headers::AccessControlAllowOrigin::Any);
  137. Ok(res)
  138. }
  139. }
  140. fn main() {
  141. let args: Vec<_> = env::args().collect();
  142. let mut port = String::from("");
  143. let mut conn_string = String::from("");
  144. if args.len() > 1 {
  145. port = args[1].as_str().to_string();
  146. conn_string = args[2].as_str().to_string();
  147. } else {
  148. panic!("{:?}", args);
  149. }
  150. println!("Connecting to postgres: {}", conn_string);
  151. let postgres_pool = db::setup_connection_pool(&conn_string, 6);
  152. let conn = postgres_pool.get().unwrap();
  153. println!("Connected to postgres");
  154. db::scaffold_db(&conn);
  155. let redis_pool = cache::setup_connection_pool("redis://localhost", 6);
  156. let mut assets_mount = Mount::new();
  157. assets_mount.mount("/", get_router())
  158. .mount("/assets/", Static::new(Path::new("../hairparty_web/")));
  159. let mut middleware = Chain::new(assets_mount);
  160. middleware.link(Read::<db::AppDb>::both(postgres_pool));
  161. middleware.link(Read::<cache::AppRedis>::both(redis_pool));
  162. middleware.link_before(Read::<bodyparser::MaxBodyLength>::one(MAX_BODY_LENGTH));
  163. middleware.link_after(CorsMiddleware);
  164. let listen = format!("0.0.0.0:{}", port);
  165. println!("{:?}", listen);
  166. Iron::new(middleware).http(listen.as_str()).unwrap();
  167. }