micro_kit/
http.rs

1use std::sync::{PoisonError};
2use std::fmt;
3use std::error::Error;
4use std::borrow::Cow;
5use std::fmt::Debug;
6
7
8use ::json;
9use ::config::{ConfigFile, ConfigError};
10
11#[derive(Debug)]
12pub enum APIError<T: Debug> {
13    PoisonError(PoisonError<T>),
14    JsonError(json::Error)
15}
16
17impl<T: Debug> fmt::Display for APIError<T> {
18    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19        match *self {
20            APIError::PoisonError(_) => f.write_str("Lock Error"),
21            APIError::JsonError(_) => f.write_str("Json encoding Error")
22        }
23    }
24}
25
26impl<T: Debug> Error for APIError<T> {
27    fn description(&self) -> &str {
28        match *self {
29            APIError::PoisonError(_) => "Lock Error",
30            APIError::JsonError(_) => "JsonError"
31        }
32    }
33
34    fn cause(&self) -> Option<&Error> {
35        match *self {
36            APIError::PoisonError(ref e) => Some(e),
37            APIError::JsonError(ref e) => Some(e)
38        }
39    }
40}
41
42pub struct APIConfig<'a> {
43    addr: Cow<'a, str>,
44    port: u16
45}
46
47impl<'a> APIConfig<'a> {
48    pub fn new(c: &'a ConfigFile) -> Result<Self, ConfigError> {
49        if !c["service"].is_badvalue() {
50            if !c["service"]["address"].is_badvalue() {
51                let service_ip = c["service"]["address"].as_str().unwrap();
52                let service_port = c["service"]["port"].as_i64().unwrap_or(8081) as u16;
53
54                Ok(APIConfig {
55                    addr: service_ip.into(),
56                    port: service_port
57                })
58            } else {
59                Err(ConfigError::MissingComponent("service -> address".to_string()))
60            }
61
62        } else {
63            Err(ConfigError::MissingComponent("service".to_string()))
64        }
65    }
66
67    pub fn get_conn(&self) -> String {
68        format!("{}:{}", self.addr, self.port)
69    }
70}