103 lines
2.5 KiB
Rust
103 lines
2.5 KiB
Rust
use serde::{Serialize, Deserialize};
|
|
use std::fs::File;
|
|
use std::str::FromStr;
|
|
use std::io::prelude::*;
|
|
use std::collections::HashMap;
|
|
pub mod server_conf;
|
|
|
|
static FILE: &str = "mrprox.conf";
|
|
|
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
|
|
pub struct ConfFile{
|
|
port: String,
|
|
port_conf: String,
|
|
servers: Vec<ServerData>,
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
|
|
pub struct ServerData{
|
|
domain: String,
|
|
ip: String,
|
|
}
|
|
|
|
pub struct Config{
|
|
l_servers : HashMap<String, String>,
|
|
port: String,
|
|
port_conf: String,
|
|
}
|
|
|
|
impl Config {
|
|
pub fn new() -> Self {
|
|
let mut file = File::open(&FILE).unwrap();
|
|
let mut s = String::new();
|
|
file.read_to_string(&mut s).unwrap();
|
|
let yam: ConfFile = serde_yaml::from_str(&s).unwrap();
|
|
Self{
|
|
l_servers: Self::get_servers(&yam.servers),
|
|
port: yam.port,
|
|
port_conf: yam.port_conf,
|
|
}
|
|
}
|
|
|
|
pub fn add(&mut self, server: ServerData){
|
|
self.l_servers.insert(server.domain, server.ip);
|
|
}
|
|
|
|
pub fn del(&mut self, domain: String) -> bool {
|
|
match self.l_servers.remove(&domain) {
|
|
Some(_s) => true,
|
|
None => false,
|
|
}
|
|
}
|
|
|
|
pub fn flush(&self){
|
|
let conf = ConfFile {
|
|
port: self.port.clone(),
|
|
port_conf: self.port_conf.clone(),
|
|
servers: Vec::from_iter(self.l_servers.iter()
|
|
.map(|(x, y)| ServerData{domain: (*x).clone(), ip: (*y).clone()})),
|
|
};
|
|
println!("{}", serde_yaml::to_string(&conf).unwrap());
|
|
|
|
}
|
|
|
|
fn get_servers(file: &Vec<ServerData>) -> HashMap<String, String> {
|
|
let mut ret = HashMap::new();
|
|
for j in file{
|
|
ret.insert(j.domain.clone(),j.ip.clone());
|
|
}
|
|
ret
|
|
}
|
|
|
|
fn get_host(&self, host: &String) -> Option<(&String, &String)>{
|
|
self.l_servers.get_key_value(host)
|
|
}
|
|
|
|
pub fn get_server(&self, host: &String) -> Option<(String, u16)>{
|
|
let raw: Vec<&str>;
|
|
match self.get_host(host){
|
|
Some(h) => raw=h.1.split(":").collect(),
|
|
None => return None,
|
|
}
|
|
|
|
if raw.len() == 2 {
|
|
|
|
match FromStr::from_str(raw[1]) {
|
|
Ok(p) => return Some((String::from(raw[0]),p)),
|
|
Err(_e) => return None,
|
|
}
|
|
} else {
|
|
return None;
|
|
}
|
|
}
|
|
|
|
pub fn get_port(&self) -> &String{
|
|
&self.port
|
|
}
|
|
|
|
pub fn get_port_conf(&self) -> &String{
|
|
&self.port_conf
|
|
}
|
|
}
|
|
|