use std;
use std::collections::HashMap;
use std::net::TcpListener;
#[derive(Hash, PartialEq)]
pub enum Method {
GET,
PUT,
POST,
DELETE,
OPTIONS
}
pub struct Request;
pub struct Response {
pub code: u16
}
#[derive(Hash)]
pub struct Endpoint {
pub(crate) method: Method,
pub(crate) path: String,
}
pub struct Api {
pub(crate) endpoints: HashMap<Endpoint, fn(Request) -> Response>
}
impl Api {
pub fn new() -> Api {
Api { endpoints : HashMap::new() }
}
pub fn add_endpoint(&mut self, method: Method, path: String, handler: fn(Request) -> Response) {
let endpoint = Endpoint { method, path };
self.endpoints.insert(endpoint, handler);
}
pub fn start(&mut self, bind_address: Option<String>, bind_port: Option<u32>) {
let hostname = bind_address.unwrap_or(String::from("127.0.0.1"));
let port = bind_port.unwrap_or(8080);
let tcp_listener = TcpListener::bind(String::from(format!("{}:{}", hostname, port))).unwrap();
for stream in tcp_listener.incoming() {
let in_stream = stream.unwrap();
println!("Connection established!");
}
}
}
impl PartialEq for Endpoint {
fn eq(&self, other: &Self) -> bool {
return self.method == other.method
&& self.path == other.path;
}
}
impl Eq for Endpoint {}
#[cfg(test)]
mod tests {
use super::*;
fn api_test_handler(_request: Request) -> Response {
println!("Received request");
Response { code: 200 }
}
#[test]
fn test_adding_an_endpoint() {
let mut api = Api::new();
api.add_endpoint(Method::GET, String::from("/api/test"), api_test_handler);
let my_model = Endpoint { method: Method::GET, path: String::from("/api/test") };
assert!(api.endpoints.contains_key(&my_model));
}
}