├── .gitignore ├── Cargo.toml ├── HEADER ├── LICENSE ├── NOTICE ├── README.md ├── README_cn.md ├── examples └── echo.rs └── src ├── app.rs ├── context.rs ├── extract.rs ├── factory.rs ├── lib.rs ├── response ├── http.rs └── mod.rs ├── router.rs └── server.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "blacktea" 3 | version = "0.1.1" 4 | description = "A new comfortable back end framework for rustaceans" 5 | authors = ["LI Rui "] 6 | readme = "README.md" 7 | keywords = ["blacktea", "http", "web", "framework", "backend"] 8 | categories = ["web-programming::http-server"] 9 | homepage = "https://blacktea.lirui.tech" 10 | repository = "https://github.com/KernelErr/blacktea" 11 | license = "Apache-2.0" 12 | edition = "2018" 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [dependencies] 17 | hyper = { version = "0.14", features = ["full"] } 18 | tokio = { version = "1", features = ["full"] } 19 | tokio-uring = { version = "0.1", optional = true } 20 | serde = "1.0.126" 21 | serde_json = "1.0.64" 22 | mime = "0.3.16" 23 | route-recognizer = "0.3.0" 24 | fnv = "1.0.7" 25 | log = "0.4" 26 | url = "2.2.2" 27 | 28 | [features] 29 | tokio_io_uring = ["tokio-uring"] 30 | 31 | [[example]] 32 | name = "echo" 33 | -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | Copyright 2021 Black Tea Authors 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | ======================================================================= 204 | Black Tea Code Reference: 205 | 206 | Some code of this project is referenced from other open source project 207 | with separate copyright notice and license terms. While using this 208 | project, you are also subjected to those license. 209 | 210 | ======================================================================== 211 | Apache 2.0 licenses 212 | ======================================================================== 213 | 214 | Black Tea used some part of code in projects below. They are licensed under 215 | Apache 2.0 license. 216 | 217 | actix/actix-web: https://github.com/actix/actix-web Apache 2.0 218 | zupzup/rust-minimal-web-service-hyper: https://github.com/zupzup/rust-minimal-web-service-hyper Apache 2.0 -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Black Tea 2 | Copyright 2021 Black Tea Authors 3 | 4 | The term "Black Tea Authors" typically references to all people took part in this project, 5 | including but not limited to contributors on GitHub. 6 | 7 | We always keep our enthusiasm on open source projects. Please respect all authors, appreciate 8 | their work, and follow the license. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Black Tea 2 | 3 | **Under heavy development, can not use in production environment.** 4 | 5 | Language: [English](./README.md) | [简体中文](./README_cn.md) 6 | 7 | > Would you like to have one cup of warm black tea? 8 | 9 | Homepage & Document: [Black Tea(Under Construction)](https://blacktea.lirui.tech/) Discord: [Black Tea](https://discord.gg/tfE8RMx8Dr) 10 | 11 | Black Tea is a new Rust back end framework based on hyper. We are enthusiastic to provide developers some enhanced features and comfortable coding experience. 12 | 13 | ## Quick Start 14 | 15 | Add dependencies in `Cargo.toml`: 16 | 17 | ```toml 18 | [dependencies] 19 | blacktea = "0.1.1" 20 | tokio = { version = "1", features = ["full"] } 21 | # Enable logging 22 | # log = "0.4" 23 | # pretty_env_logger = "0.4" 24 | ``` 25 | 26 | ## Example Code 27 | 28 | > Code below only suits with version on GitHub, for published version, please refer to Crates. 29 | 30 | ```rust 31 | use blacktea::{App, HttpResponse, Method, PathParams, Server, URLParams}; 32 | 33 | async fn url_echo(params: URLParams) -> HttpResponse { 34 | let params = params.get("msg"); 35 | if let Some(msg) = params { 36 | HttpResponse::Ok().text(&msg) 37 | } else { 38 | HttpResponse::Ok().text("Echo!") 39 | } 40 | } 41 | 42 | async fn path_echo(params: PathParams) -> HttpResponse { 43 | let params = params.find("msg"); 44 | if let Some(msg) = params { 45 | HttpResponse::Ok().text(&msg) 46 | } else { 47 | HttpResponse::Ok().text("Echo!") 48 | } 49 | } 50 | 51 | #[tokio::main] 52 | async fn main() { 53 | // Enable logging, set RUST_LOG=info 54 | // pretty_env_logger::init(); 55 | let mut server = Server::new("127.0.0.1:8080"); 56 | let mut app = App::new(); 57 | // echo?msg=hello 58 | app.add("/echo", Method::GET, url_echo); 59 | // echo/hello 60 | app.add("/echo/:msg", Method::GET, path_echo); 61 | server.mount("/v1", app); 62 | server.run().await 63 | } 64 | ``` 65 | 66 | ## License 67 | 68 | Black Tea is available under [Apache License 2.0](https://opensource.org/licenses/Apache-2.0), you are also subjected to all dependencies' licenses. 69 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 | # Black Tea 2 | 3 | **积极开发中,请勿用于生产环境。** 4 | 5 | Language: [English](./README.md) | [简体中文](./README_cn.md) 6 | 7 | > 想来一杯温暖的红茶么? 8 | 9 | 主页及文档: [Black Tea(搭建中)](https://blacktea.lirui.tech/) Discord: [Black Tea](https://discord.gg/tfE8RMx8Dr) 10 | 11 | Black Tea是一款新兴的Rust后端框架,基于hyper开发。我们致力于为开发者提供增强特性和舒适的开发体验。 12 | 13 | ## 快速开始 14 | 15 | 在`Cargo.toml`的依赖中添加: 16 | 17 | ```toml 18 | [dependencies] 19 | blacktea = "0.1.1" 20 | tokio = { version = "1", features = ["full"] } 21 | # 启用日志 22 | # log = "0.4" 23 | # pretty_env_logger = "0.4" 24 | ``` 25 | 26 | ## 样例代码 27 | 28 | > 以下代码仅适用于GitHub版本,当前版本代码请参考Crates。 29 | 30 | ```rust 31 | use blacktea::{App, HttpResponse, Method, PathParams, Server, URLParams}; 32 | 33 | async fn url_echo(params: URLParams) -> HttpResponse { 34 | let params = params.get("msg"); 35 | if let Some(msg) = params { 36 | HttpResponse::Ok().text(&msg) 37 | } else { 38 | HttpResponse::Ok().text("Echo!") 39 | } 40 | } 41 | 42 | async fn path_echo(params: PathParams) -> HttpResponse { 43 | let params = params.find("msg"); 44 | if let Some(msg) = params { 45 | HttpResponse::Ok().text(&msg) 46 | } else { 47 | HttpResponse::Ok().text("Echo!") 48 | } 49 | } 50 | 51 | #[tokio::main] 52 | async fn main() { 53 | // 启用日志,设置环境变量:RUST_LOG=info 54 | // pretty_env_logger::init(); 55 | let mut server = Server::new("127.0.0.1:8080"); 56 | let mut app = App::new(); 57 | // echo?msg=hello 58 | app.add("/echo", Method::GET, url_echo); 59 | // echo/hello 60 | app.add("/echo/:msg", Method::GET, path_echo); 61 | server.mount("/v1", app); 62 | server.run().await 63 | } 64 | ``` 65 | 66 | ## 开源协议 67 | 68 | Black Tea以[Apache License 2.0](https://opensource.org/licenses/Apache-2.0)开源,同时您也受制于所有依赖的开源协议。 69 | -------------------------------------------------------------------------------- /examples/echo.rs: -------------------------------------------------------------------------------- 1 | use blacktea::{App, HttpResponse, Method, PathParams, Server, URLParams}; 2 | 3 | async fn url_echo(params: URLParams) -> HttpResponse { 4 | let params = params.get("msg"); 5 | if let Some(msg) = params { 6 | HttpResponse::Ok().text(&msg) 7 | } else { 8 | HttpResponse::Ok().text("Echo!") 9 | } 10 | } 11 | 12 | async fn path_echo(params: PathParams) -> HttpResponse { 13 | let params = params.find("msg"); 14 | if let Some(msg) = params { 15 | HttpResponse::Ok().text(&msg) 16 | } else { 17 | HttpResponse::Ok().text("Echo!") 18 | } 19 | } 20 | 21 | #[tokio::main] 22 | async fn main() { 23 | // Enable logging, set RUST_LOG=info 24 | // pretty_env_logger::init(); 25 | let mut server = Server::new("127.0.0.1:8080"); 26 | let mut app = App::new(); 27 | // echo?msg=hello 28 | app.add("/echo", Method::GET, url_echo); 29 | // echo/hello 30 | app.add("/echo/:msg", Method::GET, path_echo); 31 | server.mount("/v1", app); 32 | server.run().await 33 | } 34 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use crate::extract::FromRequest; 16 | use crate::factory::{factory, BoxServiceFactory, Handler, HandlerService}; 17 | use crate::response::HttpResponse; 18 | use hyper::Method; 19 | use std::future::Future; 20 | 21 | pub struct App { 22 | apps: Vec, 23 | } 24 | 25 | pub struct SubApp { 26 | pub path: String, 27 | pub method: Method, 28 | pub handler: BoxServiceFactory, 29 | } 30 | 31 | impl App { 32 | pub const fn new() -> Self { 33 | Self { apps: Vec::new() } 34 | } 35 | 36 | pub fn add(&mut self, path: &str, method: Method, handler: F) 37 | where 38 | F: Handler, 39 | T: FromRequest, 40 | R: Future + Send + Sync + 'static, 41 | { 42 | let path = String::from(path); 43 | let subapp = SubApp::new(path, method, handler); 44 | self.apps.push(subapp); 45 | } 46 | 47 | pub fn apps(self) -> Vec { 48 | self.apps 49 | } 50 | } 51 | 52 | impl Default for App { 53 | fn default() -> Self { 54 | Self::new() 55 | } 56 | } 57 | 58 | impl SubApp { 59 | pub fn new(path: String, method: Method, handler: F) -> Self 60 | where 61 | F: Handler, 62 | T: FromRequest, 63 | R: Future + Send + Sync + 'static, 64 | { 65 | Self { 66 | path, 67 | method, 68 | handler: factory(HandlerService::new(handler)), 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/context.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use fnv::FnvHashMap; 16 | use hyper::{Body, Request}; 17 | use route_recognizer::Params; 18 | use url::Url; 19 | 20 | #[derive(Debug)] 21 | pub struct Context { 22 | pub req: Request, 23 | pub path_params: Params, 24 | pub url_params: FnvHashMap, 25 | } 26 | 27 | impl Context { 28 | pub fn new(req: Request, path_params: Params) -> Self { 29 | let mut hashmap = FnvHashMap::default(); 30 | let url = format!("http://localhost{}", req.uri().to_string()); 31 | let url = Url::parse(&url).unwrap(); 32 | let params = url.query_pairs(); 33 | for pair in params { 34 | let k = String::from(pair.0.as_ref()); 35 | let v = String::from(pair.1.as_ref()); 36 | hashmap.insert(k, v); 37 | } 38 | Self { 39 | req, 40 | path_params, 41 | url_params: hashmap, 42 | } 43 | } 44 | 45 | pub fn url_params(self, key: &str) -> Option { 46 | let params = self.url_params.get(key); 47 | if let Some(params) = params { 48 | let params = String::from(params); 49 | return Some(params); 50 | } 51 | None 52 | } 53 | 54 | pub fn path_params(self, key: &str) -> Option { 55 | let params = self.path_params.find(key); 56 | if let Some(params) = params { 57 | let params = String::from(params); 58 | return Some(params); 59 | } 60 | None 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/extract.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use crate::context::Context; 16 | use crate::response::HttpResponse; 17 | use hyper::header::HeaderValue; 18 | // use hyper::http::Extensions; 19 | use hyper::{Error, HeaderMap, Version}; 20 | 21 | pub type HyperResponse = hyper::Response; 22 | pub type Header = HeaderMap; 23 | pub type URL = hyper::Uri; 24 | pub type HttpVersion = Version; 25 | // pub type ProtocolExtensions = Extensions; 26 | pub type PathParams = route_recognizer::Params; 27 | pub type URLParams = fnv::FnvHashMap; 28 | 29 | pub trait IntoResponse: Send + Sync { 30 | fn into_response(self) -> HyperResponse; 31 | } 32 | 33 | impl IntoResponse for HyperResponse { 34 | fn into_response(self) -> HyperResponse { 35 | self 36 | } 37 | } 38 | 39 | impl IntoResponse for HttpResponse { 40 | fn into_response(self) -> HyperResponse { 41 | self.res() 42 | } 43 | } 44 | 45 | pub trait FromRequest: Sized + Send + Sync + 'static { 46 | type Error: Into; 47 | 48 | fn from_request(c: &Context) -> Result; 49 | } 50 | 51 | impl FromRequest for hyper::Method { 52 | type Error = Error; 53 | 54 | fn from_request(c: &Context) -> Result { 55 | Ok(c.req.method().clone()) 56 | } 57 | } 58 | 59 | impl FromRequest for URL { 60 | type Error = Error; 61 | 62 | fn from_request(c: &Context) -> Result { 63 | Ok(c.req.uri().clone()) 64 | } 65 | } 66 | 67 | impl FromRequest for HttpVersion { 68 | type Error = Error; 69 | 70 | fn from_request(c: &Context) -> Result { 71 | Ok(c.req.version()) 72 | } 73 | } 74 | 75 | impl FromRequest for Header { 76 | type Error = Error; 77 | 78 | fn from_request(c: &Context) -> Result { 79 | Ok(c.req.headers().clone()) 80 | } 81 | } 82 | 83 | impl FromRequest for PathParams { 84 | type Error = Error; 85 | 86 | fn from_request(c: &Context) -> Result { 87 | Ok(c.path_params.clone()) 88 | } 89 | } 90 | 91 | impl FromRequest for URLParams { 92 | type Error = Error; 93 | 94 | fn from_request(c: &Context) -> Result { 95 | Ok(c.url_params.clone()) 96 | } 97 | } 98 | 99 | impl FromRequest for () { 100 | type Error = Error; 101 | 102 | #[inline] 103 | fn from_request(_: &Context) -> Result { 104 | Ok(()) 105 | } 106 | } 107 | 108 | macro_rules! from_request_tuple({ $($param:ident),+} => { 109 | impl< $($param: FromRequest + 'static,)+ > FromRequest for ($($param,)+) { 110 | type Error = Error; 111 | 112 | #[inline] 113 | fn from_request(c: &Context) -> Result { 114 | Ok(($($param::from_request(c)?,)+)) 115 | } 116 | } 117 | }); 118 | 119 | from_request_tuple!(A); 120 | from_request_tuple!(A, B); 121 | from_request_tuple!(A, B, C); 122 | from_request_tuple!(A, B, C, D); 123 | from_request_tuple!(A, B, C, D, E); 124 | from_request_tuple!(A, B, C, D, E, F); 125 | from_request_tuple!(A, B, C, D, E, F, G); 126 | -------------------------------------------------------------------------------- /src/factory.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use crate::context::Context; 16 | use crate::extract::{FromRequest, IntoResponse}; 17 | use crate::response::HttpResponse; 18 | use std::boxed::Box; 19 | use std::future::Future; 20 | use std::future::{ready, Ready}; 21 | use std::marker::PhantomData; 22 | use std::pin::Pin; 23 | 24 | pub type BoxFuture = Pin + Send + Sync>>; 25 | 26 | pub trait Service: Send + Sync { 27 | type Response; 28 | type Future: Future + Send + Sync; 29 | 30 | fn call(&self, c: Context) -> Self::Future; 31 | } 32 | 33 | pub trait ServiceFactory: Send + Sync { 34 | type Response; 35 | 36 | type Future: Future; 37 | 38 | type Service: Service; 39 | 40 | fn new_service(&self) -> Self::Future; 41 | } 42 | 43 | pub type BoxService = Box>>; 44 | 45 | impl Service for BoxService { 46 | type Response = Res; 47 | type Future = BoxFuture; 48 | 49 | #[inline] 50 | fn call(&self, c: Context) -> Self::Future { 51 | (**self).call(c) 52 | } 53 | } 54 | 55 | pub fn service(service: S) -> BoxService 56 | where 57 | S: Service + 'static, 58 | S::Future: 'static, 59 | { 60 | Box::new(ServiceWrapper::new(service)) 61 | } 62 | 63 | struct ServiceWrapper { 64 | inner: S, 65 | } 66 | 67 | impl ServiceWrapper { 68 | const fn new(inner: S) -> Self { 69 | Self { inner } 70 | } 71 | } 72 | 73 | impl Service for ServiceWrapper 74 | where 75 | S: Service, 76 | S::Future: 'static, 77 | { 78 | type Response = Res; 79 | type Future = BoxFuture; 80 | 81 | // crate::forward_ready!(inner); 82 | 83 | fn call(&self, c: Context) -> Self::Future { 84 | Box::pin(self.inner.call(c)) 85 | } 86 | } 87 | 88 | struct FactoryWrapper(SF); 89 | 90 | impl ServiceFactory for FactoryWrapper 91 | where 92 | Res: 'static, 93 | SF: ServiceFactory, 94 | SF::Future: Send + Sync + 'static, 95 | SF::Service: 'static, 96 | ::Future: 'static, 97 | { 98 | type Response = Res; 99 | type Service = BoxService; 100 | type Future = BoxFuture; 101 | 102 | fn new_service(&self) -> Self::Future { 103 | let f = self.0.new_service(); 104 | Box::pin(async { Box::new(ServiceWrapper::new(f.await)) as _ }) 105 | } 106 | } 107 | 108 | pub struct BoxServiceFactory( 109 | Box< 110 | dyn ServiceFactory< 111 | Response = Res, 112 | Service = BoxService, 113 | Future = BoxFuture>, 114 | >, 115 | >, 116 | ); 117 | 118 | impl ServiceFactory for BoxServiceFactory { 119 | type Response = Res; 120 | type Service = BoxService; 121 | type Future = BoxFuture; 122 | 123 | fn new_service(&self) -> Self::Future { 124 | self.0.new_service() 125 | } 126 | } 127 | 128 | pub fn factory(factory: SF) -> BoxServiceFactory 129 | where 130 | SF: ServiceFactory + 'static, 131 | Res: 'static, 132 | SF::Response: 'static, 133 | SF::Service: 'static, 134 | SF::Future: 'static + Send + Sync, 135 | { 136 | BoxServiceFactory(Box::new(FactoryWrapper(factory))) 137 | } 138 | 139 | pub trait Handler: Send + Sync + Clone + 'static 140 | where 141 | R: Future, 142 | R::Output: IntoResponse, 143 | { 144 | fn call(&self, param: T) -> R; 145 | } 146 | 147 | pub struct HandlerService 148 | where 149 | F: Handler, 150 | T: FromRequest, 151 | R: Future, 152 | R::Output: IntoResponse, 153 | { 154 | hnd: F, 155 | _phantom: PhantomData<(T, R)>, 156 | } 157 | 158 | impl HandlerService 159 | where 160 | F: Handler, 161 | T: FromRequest, 162 | R: Future, 163 | R::Output: IntoResponse, 164 | { 165 | pub fn new(hnd: F) -> Self { 166 | Self { 167 | hnd, 168 | _phantom: PhantomData, 169 | } 170 | } 171 | } 172 | 173 | impl Clone for HandlerService 174 | where 175 | F: Handler, 176 | T: FromRequest, 177 | R: Future, 178 | R::Output: IntoResponse, 179 | { 180 | fn clone(&self) -> Self { 181 | Self { 182 | hnd: self.hnd.clone(), 183 | _phantom: PhantomData, 184 | } 185 | } 186 | } 187 | 188 | impl ServiceFactory for HandlerService 189 | where 190 | F: Handler, 191 | T: FromRequest, 192 | R: Future + Send + Sync + 'static, 193 | { 194 | type Response = HttpResponse; 195 | type Service = Self; 196 | type Future = Ready; 197 | 198 | fn new_service(&self) -> Self::Future { 199 | ready(self.clone()) 200 | } 201 | } 202 | 203 | /// HandlerService is both it's ServiceFactory and Service Type. 204 | impl Service for HandlerService 205 | where 206 | F: Handler, 207 | T: FromRequest, 208 | R: Future + Send + Sync + 'static, 209 | { 210 | type Response = HttpResponse; 211 | type Future = BoxFuture; 212 | 213 | fn call(&self, c: Context) -> Self::Future { 214 | let data = T::from_request(&c).ok().unwrap(); 215 | Box::pin(self.hnd.call(data)) 216 | } 217 | } 218 | 219 | impl Handler<(), R> for F 220 | where 221 | F: Fn() -> R + Send + Sync + Clone + 'static, 222 | 223 | R: Future, 224 | R::Output: IntoResponse, 225 | { 226 | fn call(&self, _: ()) -> R { 227 | (self)() 228 | } 229 | } 230 | macro_rules! factory_tuple({ $(($n: tt, $param:ident)),+} => { 231 | impl Handler<($($param,)+), R> for F 232 | where 233 | F: Fn($($param,)+) -> R + Send + Sync + Clone + 'static, 234 | 235 | R: Future, 236 | R::Output: IntoResponse, 237 | { 238 | fn call(&self, param: ($($param,)+)) -> R { 239 | (self)($(param.$n,)+) 240 | } 241 | } 242 | }); 243 | 244 | factory_tuple!((0, P1)); 245 | factory_tuple!((0, P1), (1, P2)); 246 | factory_tuple!((0, P1), (1, P2), (2, P3)); 247 | factory_tuple!((0, P1), (1, P2), (2, P3), (3, P4)); 248 | factory_tuple!((0, P1), (1, P2), (2, P3), (3, P4), (4, P5)); 249 | factory_tuple!((0, P1), (1, P2), (2, P3), (3, P4), (4, P5), (5, P6)); 250 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // #![deny(warnings)] 16 | #[macro_use] 17 | extern crate log; 18 | mod app; 19 | pub mod context; 20 | mod response; 21 | pub mod router; 22 | mod server; 23 | 24 | mod extract; 25 | pub mod factory; 26 | 27 | pub use self::app::App; 28 | pub use self::context::Context; 29 | pub use self::extract::HyperResponse; 30 | pub use self::response::HttpResponse; 31 | pub use self::server::{Executor, Server}; 32 | pub use extract::{Header, HttpVersion, PathParams, URLParams, URL}; 33 | pub use hyper::Method; 34 | -------------------------------------------------------------------------------- /src/response/http.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use hyper::http::response::Builder as HyperHttpResponseBuilder; 16 | use hyper::{header, Body, Response, StatusCode}; 17 | use serde::Serialize; 18 | 19 | macro_rules! status_response { 20 | ($func: ident, $status: expr) => { 21 | #[allow(non_snake_case, missing_docs)] 22 | pub fn $func() -> HttpResponseBuilder { 23 | HttpResponseBuilder::new(HyperHttpResponseBuilder::new().status($status)) 24 | } 25 | }; 26 | } 27 | 28 | pub struct HttpResponse { 29 | res: Response, 30 | } 31 | 32 | impl HttpResponse { 33 | #[inline] 34 | pub fn res(self) -> Response { 35 | self.res 36 | } 37 | 38 | #[inline] 39 | pub const fn from_builder(res: Response) -> Self { 40 | Self { res } 41 | } 42 | } 43 | 44 | pub struct HttpResponseBuilder { 45 | builder: HyperHttpResponseBuilder, 46 | } 47 | 48 | impl HttpResponseBuilder { 49 | pub const fn new(builder: HyperHttpResponseBuilder) -> Self { 50 | Self { builder } 51 | } 52 | 53 | pub fn header(self, key: &str, value: &str) -> Self { 54 | let builder = self.builder.header(key, value); 55 | Self { builder } 56 | } 57 | 58 | pub fn empty(self) -> HttpResponse { 59 | HttpResponse::from_builder(self.builder.body(Body::empty()).unwrap()) 60 | } 61 | 62 | pub fn text(self, value: &str) -> HttpResponse { 63 | let value = String::from(value); 64 | let builder = self.builder; 65 | let contains = if let Some(header) = builder.headers_ref() { 66 | header.contains_key(header::CONTENT_TYPE) 67 | } else { 68 | true 69 | }; 70 | 71 | if !contains { 72 | let builder = builder.header("Content-Type", "text/html; charset=UTF-8"); 73 | return HttpResponse::from_builder(builder.body(Body::from(value)).unwrap()); 74 | } 75 | 76 | HttpResponse::from_builder(builder.body(Body::from(value)).unwrap()) 77 | } 78 | 79 | pub fn json(self, value: impl Serialize) -> HttpResponse { 80 | let builder = self.builder; 81 | match serde_json::to_string(&value) { 82 | Ok(body) => { 83 | let contains = if let Some(header) = builder.headers_ref() { 84 | header.contains_key(header::CONTENT_TYPE) 85 | } else { 86 | true 87 | }; 88 | 89 | if !contains { 90 | let builder = 91 | builder.header("Content-Type", mime::APPLICATION_JSON.to_string()); 92 | return HttpResponse::from_builder(builder.body(Body::from(body)).unwrap()); 93 | } 94 | 95 | HttpResponse::from_builder(builder.body(Body::from(body)).unwrap()) 96 | } 97 | Err(_) => HttpResponse::from_builder( 98 | HttpResponse::InternalServerError() 99 | .builder 100 | .body(Body::from("Error")) 101 | .unwrap(), 102 | ), 103 | } 104 | } 105 | } 106 | 107 | impl HttpResponse { 108 | status_response!(Continue, StatusCode::CONTINUE); 109 | status_response!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS); 110 | status_response!(Processing, StatusCode::PROCESSING); 111 | 112 | status_response!(Ok, StatusCode::OK); 113 | status_response!(Created, StatusCode::CREATED); 114 | status_response!(Accepted, StatusCode::ACCEPTED); 115 | status_response!( 116 | NonAuthoritativeInformation, 117 | StatusCode::NON_AUTHORITATIVE_INFORMATION 118 | ); 119 | 120 | status_response!(NoContent, StatusCode::NO_CONTENT); 121 | status_response!(ResetContent, StatusCode::RESET_CONTENT); 122 | status_response!(PartialContent, StatusCode::PARTIAL_CONTENT); 123 | status_response!(MultiStatus, StatusCode::MULTI_STATUS); 124 | status_response!(AlreadyReported, StatusCode::ALREADY_REPORTED); 125 | 126 | status_response!(MultipleChoices, StatusCode::MULTIPLE_CHOICES); 127 | status_response!(MovedPermanently, StatusCode::MOVED_PERMANENTLY); 128 | status_response!(Found, StatusCode::FOUND); 129 | status_response!(SeeOther, StatusCode::SEE_OTHER); 130 | status_response!(NotModified, StatusCode::NOT_MODIFIED); 131 | status_response!(UseProxy, StatusCode::USE_PROXY); 132 | status_response!(TemporaryRedirect, StatusCode::TEMPORARY_REDIRECT); 133 | status_response!(PermanentRedirect, StatusCode::PERMANENT_REDIRECT); 134 | 135 | status_response!(BadRequest, StatusCode::BAD_REQUEST); 136 | status_response!(NotFound, StatusCode::NOT_FOUND); 137 | status_response!(Unauthorized, StatusCode::UNAUTHORIZED); 138 | status_response!(PaymentRequired, StatusCode::PAYMENT_REQUIRED); 139 | status_response!(Forbidden, StatusCode::FORBIDDEN); 140 | status_response!(MethodNotAllowed, StatusCode::METHOD_NOT_ALLOWED); 141 | status_response!(NotAcceptable, StatusCode::NOT_ACCEPTABLE); 142 | status_response!( 143 | ProxyAuthenticationRequired, 144 | StatusCode::PROXY_AUTHENTICATION_REQUIRED 145 | ); 146 | status_response!(RequestTimeout, StatusCode::REQUEST_TIMEOUT); 147 | status_response!(Conflict, StatusCode::CONFLICT); 148 | status_response!(Gone, StatusCode::GONE); 149 | status_response!(LengthRequired, StatusCode::LENGTH_REQUIRED); 150 | status_response!(PreconditionFailed, StatusCode::PRECONDITION_FAILED); 151 | status_response!(PreconditionRequired, StatusCode::PRECONDITION_REQUIRED); 152 | status_response!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE); 153 | status_response!(UriTooLong, StatusCode::URI_TOO_LONG); 154 | status_response!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE); 155 | status_response!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE); 156 | status_response!(ExpectationFailed, StatusCode::EXPECTATION_FAILED); 157 | status_response!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY); 158 | status_response!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS); 159 | status_response!( 160 | RequestHeaderFieldsTooLarge, 161 | StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE 162 | ); 163 | status_response!( 164 | UnavailableForLegalReasons, 165 | StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS 166 | ); 167 | 168 | status_response!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR); 169 | status_response!(NotImplemented, StatusCode::NOT_IMPLEMENTED); 170 | status_response!(BadGateway, StatusCode::BAD_GATEWAY); 171 | status_response!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE); 172 | status_response!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT); 173 | status_response!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED); 174 | status_response!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES); 175 | status_response!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE); 176 | status_response!(LoopDetected, StatusCode::LOOP_DETECTED); 177 | 178 | status_response!(NotExtended, StatusCode::NOT_EXTENDED); 179 | status_response!( 180 | NetworkAuthenticationRequired, 181 | StatusCode::NETWORK_AUTHENTICATION_REQUIRED 182 | ); 183 | } 184 | -------------------------------------------------------------------------------- /src/response/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | pub mod http; 16 | 17 | pub use self::http::HttpResponse; 18 | -------------------------------------------------------------------------------- /src/router.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use crate::app::SubApp; 16 | use crate::extract::FromRequest; 17 | use crate::factory::{factory, BoxServiceFactory, Handler, HandlerService}; 18 | use crate::response::HttpResponse; 19 | use fnv::FnvHashMap; 20 | use hyper::{Method, Response, StatusCode}; 21 | use route_recognizer::{Params, Router as InternalRouter}; 22 | use std::future::Future; 23 | 24 | pub struct Router { 25 | method_map: FnvHashMap>>, 26 | 27 | not_found_handler: BoxServiceFactory, 28 | } 29 | 30 | pub struct RouterMatch<'a> { 31 | pub handler: &'a BoxServiceFactory, 32 | pub params: Params, 33 | } 34 | 35 | impl Default for Router { 36 | fn default() -> Self { 37 | Self::new() 38 | } 39 | } 40 | 41 | impl Router { 42 | pub fn new() -> Self { 43 | Self { 44 | method_map: FnvHashMap::default(), 45 | not_found_handler: factory(HandlerService::new(not_found_handler)), 46 | } 47 | } 48 | 49 | pub fn add(&mut self, path: &str, method: Method, handler: F) 50 | where 51 | F: Handler, 52 | T: FromRequest, 53 | R: Future + Send + Sync + 'static, 54 | { 55 | self.method_map 56 | .entry(method) 57 | .or_insert_with(InternalRouter::new) 58 | .add(path, factory(HandlerService::new(handler))); 59 | } 60 | 61 | pub fn mount(&mut self, path: &str, sub_app: SubApp) { 62 | self.method_map 63 | .entry(sub_app.method) 64 | .or_insert_with(InternalRouter::new) 65 | .add(&format!("{}{}", path, sub_app.path), sub_app.handler); 66 | } 67 | 68 | pub fn route(&self, path: &str, method: &Method) -> RouterMatch { 69 | if let Some(m) = self 70 | .method_map 71 | .get(method) 72 | .and_then(|r| r.recognize(path).ok()) 73 | { 74 | let mut params = Params::new(); 75 | params.clone_from(m.params()); 76 | RouterMatch { 77 | handler: m.handler(), 78 | params, 79 | } 80 | } else { 81 | RouterMatch { 82 | handler: &self.not_found_handler, 83 | params: Params::new(), 84 | } 85 | } 86 | } 87 | } 88 | 89 | async fn not_found_handler() -> HttpResponse { 90 | HttpResponse::from_builder( 91 | Response::builder() 92 | .status(StatusCode::NOT_FOUND) 93 | .body("NOT FOUND".into()) 94 | .unwrap(), 95 | ) 96 | } 97 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Black Tea Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use crate::app::App; 16 | use crate::context::Context; 17 | use crate::extract::{FromRequest, IntoResponse}; 18 | use crate::factory::{Handler, ServiceFactory}; 19 | use crate::response::HttpResponse; 20 | use crate::router::Router; 21 | use core::str; 22 | use hyper::server::conn::AddrStream; 23 | use hyper::service::make_service_fn; 24 | use hyper::service::service_fn; 25 | use hyper::Body; 26 | use hyper::Method; 27 | use hyper::Request; 28 | use hyper::Server as HyperServer; 29 | use std::future::Future; 30 | use std::net::SocketAddr; 31 | use std::sync::Arc; 32 | 33 | type Response = hyper::Response; 34 | type Error = Box; 35 | 36 | /// https://github.com/hyperium/hyper/blob/19f38b3e7febadedbfc558d17fa41baff73c6ecc/src/common/exec.rs#L28-L57 37 | pub enum Executor { 38 | Tokio, 39 | #[cfg(feature = "tokio_io_uring")] 40 | TokioUring, 41 | } 42 | 43 | impl Default for Executor { 44 | fn default() -> Self { 45 | Self::Tokio 46 | } 47 | } 48 | 49 | #[cfg(feature = "tokio_io_uring")] 50 | #[derive(Clone)] 51 | struct TokioUringExecutor; 52 | 53 | #[cfg(feature = "tokio_io_uring")] 54 | impl hyper::rt::Executor for TokioUringExecutor 55 | where 56 | F: Future + 'static, 57 | F::Output: 'static, 58 | { 59 | fn execute(&self, fut: F) { 60 | tokio_uring::spawn(fut); 61 | } 62 | } 63 | 64 | pub struct Server { 65 | addr: SocketAddr, 66 | router: Router, 67 | executor: Executor, 68 | } 69 | 70 | impl Server { 71 | #[inline] 72 | pub fn new(addr: &str) -> Self { 73 | let addr = String::from(addr); 74 | let addr: SocketAddr = addr.parse().expect("Failed to parse server address."); 75 | Self { 76 | addr, 77 | router: Router::new(), 78 | executor: Executor::default(), 79 | } 80 | } 81 | 82 | pub fn set_executor(&mut self, executor: Executor) { 83 | self.executor = executor; 84 | } 85 | 86 | pub fn service(&mut self, path: &str, method: Method, handler: F) 87 | where 88 | F: Handler + Send + Sync + 'static, 89 | T: FromRequest + Send + Sync + 'static, 90 | R: Future + Send + Sync + 'static, 91 | { 92 | self.router.add(path, method, handler); 93 | } 94 | 95 | pub fn mount(&mut self, mount_point: &str, app: App) { 96 | for subapp in app.apps() { 97 | self.router.mount(mount_point, subapp); 98 | } 99 | } 100 | 101 | pub async fn run(self) { 102 | let shared_router = Arc::new(self.router); 103 | match self.executor { 104 | Executor::Tokio => { 105 | let service = make_service_fn(move |conn: &AddrStream| { 106 | let addr: String = conn.remote_addr().to_string(); 107 | let router_capture = shared_router.clone(); 108 | async { 109 | Ok::<_, Error>(service_fn(move |req| { 110 | route(router_capture.clone(), addr.clone(), req) 111 | })) 112 | } 113 | }); 114 | let server = HyperServer::bind(&self.addr).serve(service); 115 | info!("Listening on http://{}", self.addr); 116 | let _ = server.await; 117 | } 118 | #[cfg(feature = "tokio_io_uring")] 119 | Executor::TokioUring => { 120 | let listener = tokio::net::TcpListener::bind(self.addr) 121 | .await 122 | .expect("bind failed"); 123 | let server = hyper::server::conn::Http::new().with_executor(TokioUringExecutor); 124 | while let Ok((stream, addr)) = listener.accept().await { 125 | let router_capture = shared_router.clone(); 126 | server 127 | .serve_connection( 128 | stream, 129 | service_fn(move |req| { 130 | route(router_capture.clone(), addr.to_string(), req) 131 | }), 132 | ) 133 | .await 134 | .expect("error in serve_connection"); 135 | } 136 | } 137 | } 138 | } 139 | } 140 | 141 | async fn route(router: Arc, addr: String, req: Request) -> Result { 142 | info!("{} {} {}", req.method(), req.uri(), addr); 143 | let found_handler = router.route(req.uri().path(), req.method()); 144 | let res = found_handler 145 | .handler 146 | .new_service() 147 | .await 148 | .call(Context::new(req, found_handler.params)) 149 | .await 150 | .into_response(); 151 | Ok(res) 152 | } 153 | --------------------------------------------------------------------------------