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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
use std::sync::Arc; use std::rc::Rc; use regex::Regex; use futures::future::Future; use futures_cpupool::CpuPool; use hyper::server::{Http, Request, Response, Service}; use hyper; use queen_log::color::Print; use error::Result; pub use self::route::Route; pub use self::group::Group; use self::middleware::Middleware; use self::context::Context; #[macro_use] mod macros; mod route; mod group; pub mod middleware; pub mod context; pub type Handle = Fn(&mut Context) + Send + Sync + 'static; pub struct App { groups: Vec<Group>, begin: Vec<Middleware>, before: Vec<Middleware>, after: Vec<Middleware>, finish: Vec<Middleware>, not_found: Option<Middleware> } impl App { pub fn new() -> App { App { groups: vec![Group::new("")], begin: Vec::new(), before: Vec::new(), after: Vec::new(), finish: Vec::new(), not_found: None } } fn add<H>(&mut self, method: &str, pattern: &str, handle: H) -> &mut Route where H: Fn(&mut Context) + Send + Sync + 'static { let route = Route::new( method.parse().unwrap(), pattern.into(), Box::new(handle), ); self.groups.get_mut(0).unwrap().routes.push(route); self.groups.get_mut(0).unwrap().routes.last_mut().unwrap() } route!(get); route!(put); route!(post); route!(head); route!(delete); route!(options); route!(connect); pub fn mount<F>(&mut self, func: F) where F: Fn() -> Group { let group = func(); self.groups.push(group) } middleware!(begin); middleware!(before); middleware!(after); middleware!(finish); pub fn use_middleware<F>(&mut self, func: F) where F: Fn(&mut App) { func(self) } pub fn not_found<H>(&mut self, handle: H) where H: Fn(&mut Context) + Send + Sync + 'static { self.not_found = Some(Middleware { inner: Box::new(handle), }); } pub fn handle(&self, request: Request) -> Response { let mut context = Context::new(self, request); let mut route_found = false; for begin in self.begin.iter() { begin.execute_always(&mut context); } if context.next() { 'outer: for group in self.groups.iter() { for route in group.routes.iter() { if route.method() != context.request.method() { continue; } let path = { let path = context.request.uri().path(); if path != "/" { path.trim_right_matches('/').to_owned() } else { path.to_owned() } }; let pattern = { let pattern = route.compilied_pattern(); if pattern != "/" { pattern.trim_right_matches('/').to_owned() } else { pattern } }; if pattern.contains("^") { let re = Regex::new(&pattern).unwrap(); let caps = re.captures(&path); if let Some(caps) = caps { route_found = true; let matches = route.path(); for (key, value) in matches.iter() { context.request.params().insert(key.to_owned(), caps.get(*value).unwrap().as_str().to_owned()); } } } else { if pattern == path { route_found = true; } } if route_found { for before in self.before.iter() { before.execute(&mut context); } for before in group.before.iter() { before.execute(&mut context); } route.execute(&mut context); for after in group.after.iter() { after.execute(&mut context); } for after in self.after.iter() { after.execute(&mut context); } break 'outer; } } } if !route_found { if let Some(ref not_found) = self.not_found { not_found.execute(&mut context); } else { context.response.status_code(404).from_text("Not Found").unwrap(); } } } for finish in self.finish.iter() { finish.execute_always(&mut context); } context.finish() } pub fn run(self, addr: &str, thread_size: usize) -> Result<()> { let app_service = AppService { inner: Arc::new(self), thread_pool: CpuPool::new(thread_size) }; let app = Rc::new(app_service); let sincere_logo = Print::green( r" __.._.. . __ .___.__ .___ (__ | |\ |/ `[__ [__)[__ .__)_|_| \|\__.[___| \[___ " ); println!("{}", sincere_logo); println!( " {}{} {} {} {}", Print::green("Server running at http://"), Print::green(addr), Print::green("on"), Print::green(thread_size), Print::green("threads.") ); let addr = addr.parse().expect("Address is not valid"); let server = Http::new().bind(&addr, move || Ok(app.clone()))?; server.run()?; Ok(()) } } struct AppService { inner: Arc<App>, thread_pool: CpuPool } impl Service for AppService { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = Box<Future<Item=Self::Response, Error=Self::Error>>; fn call(&self, request: Request) -> Self::Future { let app = self.inner.clone(); let msg = self.thread_pool.spawn_fn(move || { let response = app.handle(request); Ok(response) }); Box::new(msg) } }