Update dependencies
[recipes.git] / backend / src / main.rs
1 use std::io::prelude::*;
2 use std::{fs::File, env::args};
3
4 use actix_files as fs;
5 use actix_web::{web, middleware, App, HttpServer, HttpResponse, Result, web::Query, middleware::Logger};
6
7 use askama::Template;
8 use listenfd::ListenFd;
9 use ron::de::from_reader;
10 use serde::Deserialize;
11 use env_logger;
12
13 use itertools::Itertools;
14
15 mod consts;
16 mod db;
17
18 #[derive(Template)]
19 #[template(path = "main.html")]
20 struct MainTemplate<'a> {
21 test: &'a str,
22 }
23
24 #[derive(Deserialize)]
25 pub struct Request {
26 m: Option<String>
27 }
28
29 fn main_page(query: Query<Request>) -> Result<HttpResponse> {
30
31 let main_template = MainTemplate { test: &"*** test ***" };
32
33 let s = main_template.render().unwrap();
34 Ok(HttpResponse::Ok().content_type("text/html").body(s))
35 }
36
37 #[derive(Debug, Deserialize)]
38 struct Config {
39 port: u16
40 }
41
42 fn get_exe_name() -> String {
43 let first_arg = std::env::args().nth(0).unwrap();
44 let sep: &[_] = &['\\', '/'];
45 first_arg[first_arg.rfind(sep).unwrap()+1..].to_string()
46 }
47
48 fn main() -> std::io::Result<()> {
49 if process_args() { return Ok(()) }
50
51 println!("Starting RUP as web server...");
52
53 let config: Config = {
54 let f = File::open(consts::FILE_CONF).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
55 match from_reader(f) {
56 Ok(c) => c,
57 Err(e) => panic!("Failed to load config: {}", e)
58 }
59 };
60
61 println!("Configuration: {:?}", config);
62
63 // let database_connection = db::create_or_update();
64
65 std::env::set_var("RUST_LOG", "actix_web=info");
66 env_logger::init();
67
68 let mut listenfd = ListenFd::from_env();
69 let mut server =
70 HttpServer::new(
71 || {
72 App::new()
73 .wrap(middleware::Compress::default())
74 .wrap(Logger::default())
75 .wrap(Logger::new("%a %{User-Agent}i"))
76 .service(web::resource("/").to(main_page))
77 .service(fs::Files::new("/static", "static").show_files_listing())
78 }
79 );
80
81 server =
82 if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
83 server.listen(l).unwrap()
84 } else {
85 server.bind(&format!("0.0.0.0:{}", config.port)).unwrap()
86 };
87
88 server.run()
89 }
90
91 fn process_args() -> bool {
92 fn print_usage() {
93 println!("Usage:");
94 println!(" {} [--help] [--test]", get_exe_name());
95 }
96
97 let args: Vec<String> = args().collect();
98
99 if args.iter().any(|arg| arg == "--help") {
100 print_usage();
101 return true
102 } else if args.iter().any(|arg| arg == "--test") {
103 let database_connection = db::create_or_update();
104 return true
105 }
106
107 false
108 }