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