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 65 66 67 68 69 70
use std::sync::{PoisonError}; use std::fmt; use std::error::Error; use std::borrow::Cow; use std::fmt::Debug; use ::json; use ::config::{ConfigFile, ConfigError}; #[derive(Debug)] pub enum APIError<T: Debug> { PoisonError(PoisonError<T>), JsonError(json::Error) } impl<T: Debug> fmt::Display for APIError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { APIError::PoisonError(_) => f.write_str("Lock Error"), APIError::JsonError(_) => f.write_str("Json encoding Error") } } } impl<T: Debug> Error for APIError<T> { fn description(&self) -> &str { match *self { APIError::PoisonError(_) => "Lock Error", APIError::JsonError(_) => "JsonError" } } fn cause(&self) -> Option<&Error> { match *self { APIError::PoisonError(ref e) => Some(e), APIError::JsonError(ref e) => Some(e) } } } pub struct APIConfig<'a> { addr: Cow<'a, str>, port: u16 } impl<'a> APIConfig<'a> { pub fn new(c: &'a ConfigFile) -> Result<Self, ConfigError> { if !c["service"].is_badvalue() { if !c["service"]["address"].is_badvalue() { let service_ip = c["service"]["address"].as_str().unwrap(); let service_port = c["service"]["port"].as_i64().unwrap_or(8081) as u16; Ok(APIConfig { addr: service_ip.into(), port: service_port }) } else { Err(ConfigError::MissingComponent("service -> address".to_string())) } } else { Err(ConfigError::MissingComponent("service".to_string())) } } pub fn get_conn(&self) -> String { format!("{}:{}", self.addr, self.port) } }