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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::collections::HashMap;
use std::sync::{
    MutexGuard,
    Mutex,
    Arc
};

type Map = HashMap<String, String>;
pub type Conn = Arc<BearConnection>;
pub type Body = String;

#[derive(Default)]
pub struct BearConnection {
    // requested host
    pub method: Method,
    pub path: String,
    pub path_info: Vec<String>,
    pub req_query: Map,
    pub req_headers: Map,
    pub req_body: Body,
    // defining response data
    pub resp_config: Mutex<Resp>
}
impl BearConnection {
    pub fn method(&self) -> &Method {
        &self.method
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn headers(&self) -> &Map {
        &self.req_headers
    }

    pub fn body(&self) -> &Body {
        &self.req_body
    }

    pub fn path_info(&self) -> &Vec<String> {
        &self.path_info
    }

    pub fn path_info_match(&self) -> Vec<&str> {
        let mut vec = Vec::with_capacity(32);
        for i in self.path_info().iter() {
            vec.push(i.as_str())
        }
        vec
    }

    // responses
    pub fn mut_resp(&self) -> MutexGuard<Resp> {
        self
            .resp_config
            .lock()
            .unwrap()
    }

    pub fn halt(&self) -> bool {
        match self.resp_config.lock() {
            Ok(e) => {
                e.is_reply_set
            },
            Err(_) => false
        }
    }
}

// default was implemented manually
pub struct Resp {
    pub status: u16,
    pub headers: Map,
    pub body: String,
    pub is_reply_set: bool
}

impl Resp {
    pub fn set_resp(&mut self, status: u16, body: impl ToString) {
        self.status = status;
        self.body = body.to_string();
        self.is_reply_set = true;
    }
    pub fn set_headers(&mut self, key: String, value: String) {
        self.headers.insert(key, value);
    }
}

impl Default for Resp {
    fn default() -> Self {
        Self {
            status: 404,
            headers: Map::with_capacity(16),
            body: String::with_capacity(2 * 1024),
            is_reply_set: false
        }
    }
}

#[derive(Debug)]
pub enum Method {
    GET,
    PUT,
    POST,
    HEAD,
    TRACE,
    PATCH,
    DELETE,
    OPTIONS,
    CONNECT,
    Unknown(Box<String>)
}

impl Default for Method {
    fn default() -> Self {
        Method::GET
    }
}