1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::collections::HashMap;
use lazy_static::*;
use config::{Config, File, FileFormat};
use handlebars::Handlebars;
use serde_json::value::{Map, Value as Json};
use reqwest::Url;

pub mod todo_server;
pub mod log;
pub mod filters;
pub mod handlers;

// initialize: application settings 
lazy_static!{
    // pull-in todo specific settings from Settings.toml 
    static ref SETTINGS: HashMap<String, String> = get_settings();
    static ref TEMPLATES: Handlebars<'static> = get_templates();
}

// Extract Todo Specific settings from Settings.toml
fn get_settings() -> HashMap<String, String> {
    let mut config = Config::default();
    config.merge(File::new("Settings", FileFormat::Toml)).unwrap();
    let settings = config.try_into::<HashMap<String, String>>().unwrap(); // Deserialize entire file contents
    settings
}

pub fn config(key: &str) -> String {
    SETTINGS.get(key).unwrap().to_string()
}

fn get_templates() -> Handlebars<'static> {
    let mut hb = Handlebars::new();
    hb.register_template_file("index", "./templates/index.hbs").unwrap();
    hb.register_template_file("todos_page", "./templates/todos_page.hbs").unwrap();
    hb.register_template_file("todo_page", "./templates/todo_page.hbs").unwrap();
    hb    
}

pub fn render(template_name: &str, data: &Map<String, Json>) -> String {
    TEMPLATES.render(template_name, data)
        .unwrap_or_else(|err| err.to_string())
}

pub fn app_server_url() -> Url {
    let ip = config("app_server_ip_address");
    let path = config("app_server_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    println!("app_server_url: {}", url);
    url
}

pub fn app_server_url_with(addl_path: &str) -> Url {
    let ip = config("app_server_ip_address");
    let mut path = config("app_server_path");
    if addl_path.len() > 0 {
        path = path.to_owned() + "/" + addl_path;
    }
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    println!("app_server_url: {}", url);
    url
}