├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── README.tpl ├── examples └── route.rs └── src ├── fs.rs ├── lib.rs ├── path.rs ├── reverse_router.rs ├── routebuilder.rs ├── router.rs ├── routesegment.rs └── util.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | 10 | jobs: 11 | rustfmt: 12 | name: Rust fmt 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | rust: 17 | - stable 18 | steps: 19 | - uses: actions/checkout@v2 20 | - uses: actions-rs/toolchain@v1 21 | with: 22 | profile: minimal 23 | toolchain: ${{ matrix.rust }} 24 | override: true 25 | - run: rustup component add rustfmt 26 | - uses: actions-rs/cargo@v1 27 | with: 28 | command: fmt 29 | args: --all -- --check 30 | 31 | check: 32 | name: Check for warnings 33 | runs-on: ubuntu-latest 34 | strategy: 35 | matrix: 36 | rust: 37 | - stable 38 | - beta 39 | - 1.46 40 | steps: 41 | - uses: actions/checkout@v2 42 | - uses: actions-rs/toolchain@v1 43 | with: 44 | profile: minimal 45 | toolchain: ${{ matrix.rust }} 46 | override: true 47 | - name: set rust options to fail on warnings 48 | run: echo "RUSTFLAGS=-D warnings" >> $GITHUB_ENV 49 | - uses: actions-rs/cargo@v1 50 | with: 51 | command: check 52 | 53 | test: 54 | name: Test 55 | runs-on: ubuntu-latest 56 | strategy: 57 | matrix: 58 | rust: 59 | - stable 60 | - beta 61 | - 1.46 62 | steps: 63 | - uses: actions/checkout@v2 64 | - uses: actions-rs/toolchain@v1 65 | with: 66 | profile: minimal 67 | toolchain: ${{ matrix.rust }} 68 | override: true 69 | - uses: actions-rs/cargo@v1 70 | with: 71 | command: test 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tide-fluent-routes" 3 | version = "0.1.5" 4 | edition = "2018" 5 | rust-version = "1.46" 6 | 7 | authors = ["Mendelt Siebenga "] 8 | license = "MIT/Apache-2.0" 9 | description = "Tide fluent routes is a library that implements a fluent routing API for Tide" 10 | repository = "https://github.com/mendelt/tide-fluent-routes" 11 | categories = ["network-programming", "web-programming::http-server"] 12 | keywords = ["tide", "http", "web", "routing"] 13 | readme = "README.md" 14 | 15 | [dependencies] 16 | tide = "0.16" 17 | log = "0.4" 18 | async-std = "1.9" 19 | 20 | [dev-dependencies] 21 | async-std = { version = "1.9", features = ["attributes"] } 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Mendelt Siebenga 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tide Fluent Routes   [![Build Status](https://github.com/mendelt/tide-fluent-routes/workflows/Build/badge.svg)](https://github.com/mendelt/tide-fluent-routes/actions?query=workflow%3ABuild+event%3Apush+branch%3Amaster) 2 | 3 | Tide Fluent Routes is a fluent api to define routes for the Tide HTTP framework. 4 | At the moment it supports setting up paths, you can integrate middleware at any place in the 5 | route-tree and you can integrate endpoints. 6 | Some things that are possible with Tide-native routes are not (yet) possible; 7 | - Tide prefix routes are not implemented 8 | - you can not nest Tide servers 9 | 10 | To use this you can import Tide Fluent Routes with `use tide_fluent_routes::prelude::*` it 11 | introduces the `register` extension method on the `Tide::Server` to register routes from a 12 | RouteBuilder. 13 | A RouteBuilder can be initialized using the `route()` method. 14 | You can register simple endpoints like this; 15 | ```rust 16 | use tide_fluent_routes::prelude::*; 17 | 18 | let mut server = tide::Server::new(); 19 | 20 | server.register( 21 | root() 22 | .get(endpoint) 23 | .post(endpoint)); 24 | ``` 25 | Fluent Routes follows conventions from Tide. All HTTP verbs are supported the same way. Paths 26 | can be extended using `at` but this method takes a router closure that allows building the route 27 | as a tree. 28 | A complete route tree can be defined like this; 29 | ```rust 30 | 31 | server.register( 32 | root() 33 | .get(endpoint) 34 | .post(endpoint) 35 | .at("api/v1", |route| route 36 | .get(endpoint) 37 | .post(endpoint) 38 | ) 39 | .at("api/v2", |route| route 40 | .get(endpoint) 41 | .post(endpoint) 42 | ) 43 | ); 44 | ``` 45 | This eliminates the need to introduce variables for partial pieces of your route tree. 46 | 47 | Including routes defined in other functions also looks very natural, this makes it easy 48 | to compose large route trees from smaller trees defined elsewhere; 49 | ```rust 50 | 51 | fn v1_routes(routes: RouteSegment<()>) -> RouteSegment<()> { 52 | routes 53 | .at("articles", |route| route 54 | .get(endpoint) 55 | .post(endpoint) 56 | .at(":id", |route| route 57 | .get(endpoint) 58 | .put(endpoint) 59 | .delete(endpoint) 60 | ) 61 | ) 62 | } 63 | 64 | fn v2_routes(routes: RouteSegment<()>) -> RouteSegment<()> { 65 | routes 66 | .at("articles", |route| route 67 | .get(endpoint)) 68 | } 69 | 70 | server.register( 71 | root() 72 | .get(endpoint) 73 | .post(endpoint) 74 | .at("api/v1", v1_routes) 75 | .at("api/v2", v2_routes)); 76 | ``` 77 | 78 | With vanilla Tide routes it can be hard to see what middleware is active for what 79 | endpoints. 80 | Adding middleware to a tree is easy, and its very clear where the middleware is applied; 81 | ```rust 82 | server.register( 83 | root() 84 | .get(endpoint) 85 | .post(endpoint) 86 | .at("api/v1", |route| route 87 | .with(dummy_middleware, |route| route 88 | .get(endpoint) 89 | ) 90 | .post(endpoint) 91 | ) 92 | .at("api/v2", |route| route 93 | .get(endpoint) 94 | .get(endpoint) 95 | ), 96 | ); 97 | ``` 98 | 99 | Serving directories is possible using `serve_dir`, this works the same as with normal Tide routes, 100 | fluent routes adds the `serve_file` convenience method for serving single files. 101 | ```rust 102 | use tide_fluent_routes::prelude::*; 103 | use tide_fluent_routes::fs::ServeFs; 104 | 105 | let mut server = tide::Server::new(); 106 | 107 | server.register( 108 | root() 109 | .serve_file("files/index.html").unwrap() 110 | .at("img", |r| r 111 | .serve_dir("files/images").unwrap() 112 | ) 113 | ); 114 | ``` 115 | 116 | *version: 0.1.3* 117 | ## License 118 | 119 | Licensed under either of 120 | 121 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 122 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 123 | 124 | at your option. 125 | 126 | ### Contribution 127 | 128 | Unless you explicitly state otherwise, any contribution intentionally submitted 129 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 130 | additional terms or conditions. 131 | -------------------------------------------------------------------------------- /README.tpl: -------------------------------------------------------------------------------- 1 | # Tide Fluent Routes   [![Build Status](https://github.com/mendelt/tide-fluent-routes/workflows/Build/badge.svg)](https://github.com/mendelt/tide-fluent-routes/actions?query=workflow%3ABuild+event%3Apush+branch%3Amaster) 2 | 3 | {{readme}} 4 | 5 | *version: {{version}}* 6 | ## License 7 | 8 | Licensed under either of 9 | 10 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 11 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 12 | 13 | at your option. 14 | 15 | ### Contribution 16 | 17 | Unless you explicitly state otherwise, any contribution intentionally submitted 18 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 19 | additional terms or conditions. 20 | -------------------------------------------------------------------------------- /examples/route.rs: -------------------------------------------------------------------------------- 1 | //! Example application showing fluent routing 2 | 3 | use tide::{Request, Result}; 4 | use tide_fluent_routes::prelude::*; 5 | 6 | #[async_std::main] 7 | async fn main() { 8 | let mut server = tide::Server::new(); 9 | server 10 | .register( 11 | root() 12 | .get(endpoint) 13 | .post(endpoint) 14 | .at("api/v1", |route| route.get(endpoint).post(endpoint)) 15 | .at("api/v2", |route| route.get(endpoint).post(endpoint)), 16 | ) 17 | .expect("Error setting up routes"); 18 | 19 | server.listen("127.0.0.1:8080").await.unwrap(); 20 | } 21 | 22 | async fn endpoint(_: Request<()>) -> Result { 23 | todo!() 24 | } 25 | -------------------------------------------------------------------------------- /src/fs.rs: -------------------------------------------------------------------------------- 1 | //! Extension traits and endpoints for serving content from the file system 2 | 3 | use crate::prelude::*; 4 | use async_std::path::PathBuf as AsyncPathBuf; 5 | use log; 6 | use std::ffi::OsStr; 7 | use std::io; 8 | use std::path::Path; 9 | use tide::Body; 10 | use tide::Response; 11 | use tide::{utils::async_trait, Endpoint}; 12 | use tide::{Request, Result, StatusCode}; 13 | 14 | /// Extension methods for the routebuilder to serving files and directories 15 | pub trait ServeFs: RouteBuilder { 16 | /// Serve a directory at a location 17 | fn serve_dir(self, dir_path: impl AsRef) -> io::Result { 18 | let endpoint = ServeDir::serve(dir_path, "*path")?; 19 | Ok(self.at("*path", |route| route.get(endpoint))) 20 | } 21 | 22 | /// Same as serve_dir, but for a single file 23 | fn serve_file(self, file_path: impl AsRef) -> io::Result { 24 | Ok(self.get(ServeFile::serve(file_path)?)) 25 | } 26 | } 27 | 28 | impl> ServeFs for R {} 29 | 30 | /// Endpoint for serving a directory 31 | #[derive(Clone, Debug, PartialEq)] 32 | pub struct ServeDir { 33 | dir_path: AsyncPathBuf, 34 | pattern: String, 35 | } 36 | 37 | impl ServeDir { 38 | /// Construct an endpoint for serving a directory. dir_path is the path of the directory to serve 39 | /// pattern is the name of the pattern from the request. 40 | fn serve(dir_path: impl AsRef, pattern: &str) -> io::Result { 41 | Ok(Self { 42 | dir_path: AsyncPathBuf::from(dir_path.as_ref().to_owned().canonicalize()?), 43 | pattern: pattern.to_string(), 44 | }) 45 | } 46 | } 47 | 48 | #[async_trait] 49 | impl Endpoint for ServeDir { 50 | async fn call(&self, req: Request) -> Result { 51 | let path = req.param(&self.pattern)?.trim_start_matches('/'); 52 | 53 | let mut file_path = self.dir_path.clone(); 54 | for path_segment in Path::new(path) { 55 | if path_segment == OsStr::new(".") { 56 | continue; 57 | } else if path_segment == OsStr::new("..") { 58 | file_path.pop(); 59 | } else { 60 | file_path.push(&path_segment); 61 | } 62 | } 63 | 64 | log::info!("Requested file: {:?}", file_path); 65 | 66 | if !file_path.starts_with(&self.dir_path) { 67 | log::warn!("Unauthorized attempt to read: {:?}", file_path); 68 | Ok(Response::new(StatusCode::Forbidden)) 69 | } else { 70 | match Body::from_file(&file_path).await { 71 | Ok(body) => Ok(Response::builder(StatusCode::Ok).body(body).build()), 72 | Err(e) if e.kind() == io::ErrorKind::NotFound => { 73 | Ok(Response::new(StatusCode::NotFound)) 74 | } 75 | Err(e) => Err(e.into()), 76 | } 77 | } 78 | } 79 | } 80 | 81 | /// Endpoint for serving files, file_path is the path to the file to serve 82 | #[derive(Clone, Debug, PartialEq)] 83 | pub struct ServeFile { 84 | file_path: AsyncPathBuf, 85 | } 86 | 87 | impl ServeFile { 88 | fn serve(file_path: impl AsRef) -> io::Result { 89 | Ok(Self { 90 | file_path: AsyncPathBuf::from(file_path.as_ref().to_owned().canonicalize()?), 91 | }) 92 | } 93 | } 94 | 95 | #[async_trait] 96 | impl Endpoint for ServeFile { 97 | async fn call(&self, _req: Request) -> Result { 98 | match Body::from_file(&self.file_path).await { 99 | Ok(body) => Ok(Response::builder(StatusCode::Ok).body(body).build()), 100 | Err(e) if e.kind() == io::ErrorKind::NotFound => { 101 | Ok(Response::new(StatusCode::NotFound)) 102 | } 103 | Err(e) => Err(e.into()), 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Tide Fluent Routes is a fluent api to define routes for the Tide HTTP framework. 2 | //! At the moment it supports setting up paths, you can integrate middleware at any place in the 3 | //! route-tree and you can integrate endpoints. 4 | //! Some things that are possible with Tide-native routes are not (yet) possible; 5 | //! - Tide prefix routes are not implemented 6 | //! - you can not nest Tide servers 7 | //! 8 | //! To use this you can import Tide Fluent Routes with `use tide_fluent_routes::prelude::*` it 9 | //! introduces the `register` extension method on the `Tide::Server` to register routes from a 10 | //! RouteBuilder. 11 | //! A RouteBuilder can be initialized using the `route()` method. 12 | //! You can register simple endpoints like this; 13 | //! ```rust 14 | //! # use tide::{Request, Result}; 15 | //! # pub async fn endpoint(_: Request<()>) -> Result { 16 | //! # todo!() 17 | //! # } 18 | //! use tide_fluent_routes::prelude::*; 19 | //! 20 | //! let mut server = tide::Server::new(); 21 | //! 22 | //! server.register( 23 | //! root() 24 | //! .get(endpoint) 25 | //! .post(endpoint) 26 | //! ).expect("Error setting up routes"); 27 | //! ``` 28 | //! Fluent Routes follows conventions from Tide. All HTTP verbs are supported the same way. Paths 29 | //! can be extended using `at` but this method takes a router closure that allows building the route 30 | //! as a tree. 31 | //! A complete route tree can be defined like this; 32 | //! ```rust 33 | //! # use tide::{Request, Result}; 34 | //! # use tide_fluent_routes::prelude::*; 35 | //! # async fn endpoint(_: Request<()>) -> Result { 36 | //! # todo!() 37 | //! # } 38 | //! # let mut server = tide::Server::new(); 39 | //! 40 | //! server.register( 41 | //! root() 42 | //! .get(endpoint) 43 | //! .post(endpoint) 44 | //! .at("api/v1", |route| route 45 | //! .get(endpoint) 46 | //! .post(endpoint) 47 | //! ) 48 | //! .at("api/v2", |route| route 49 | //! .get(endpoint) 50 | //! .post(endpoint) 51 | //! ) 52 | //! ).expect("Error setting up routes"); 53 | //! ``` 54 | //! This eliminates the need to introduce variables for partial pieces of your route tree. 55 | //! 56 | //! Including routes defined in other functions also looks very natural, this makes it easy 57 | //! to compose large route trees from smaller trees defined elsewhere; 58 | //! ```rust 59 | //! # use tide::{Request, Result}; 60 | //! # use tide_fluent_routes::prelude::*; 61 | //! # async fn endpoint(_: Request<()>) -> Result { 62 | //! # todo!() 63 | //! # } 64 | //! # let mut server = tide::Server::new(); 65 | //! 66 | //! fn v1_routes(routes: SubRoute<()>) -> SubRoute<()> { 67 | //! routes 68 | //! .at("articles", |route| route 69 | //! .get(endpoint) 70 | //! .post(endpoint) 71 | //! .at(":id", |route| route 72 | //! .get(endpoint) 73 | //! .put(endpoint) 74 | //! .delete(endpoint) 75 | //! ) 76 | //! ) 77 | //! } 78 | //! 79 | //! fn v2_routes(routes: SubRoute<()>) -> SubRoute<()> { 80 | //! routes 81 | //! .at("articles", |route| route 82 | //! .get(endpoint)) 83 | //! } 84 | //! 85 | //! server.register( 86 | //! root() 87 | //! .get(endpoint) 88 | //! .post(endpoint) 89 | //! .at("api/v1", v1_routes) 90 | //! .at("api/v2", v2_routes) 91 | //! ).expect("Error setting up routes"); 92 | //! ``` 93 | //! 94 | //! With vanilla Tide routes it can be hard to see what middleware is active for what 95 | //! endpoints. 96 | //! Adding middleware to a tree is easy, and its very clear where the middleware is applied; 97 | //! ```rust 98 | //! # use std::{future::Future, pin::Pin}; 99 | //! # use tide::{Next, Request, Result}; 100 | //! # use tide_fluent_routes::prelude::*; 101 | //! # async fn endpoint(_: Request<()>) -> Result { 102 | //! # todo!() 103 | //! # } 104 | //! # fn dummy_middleware<'a>( 105 | //! # request: Request<()>, 106 | //! # next: Next<'a, ()>, 107 | //! # ) -> Pin + Send + 'a>> { 108 | //! # Box::pin(async { Ok(next.run(request).await) }) 109 | //! # } 110 | //! # let mut server = tide::Server::new(); 111 | //! server.register( 112 | //! root() 113 | //! .get(endpoint) 114 | //! .post(endpoint) 115 | //! .at("api/v1", |route| route 116 | //! .with(dummy_middleware, |route| route 117 | //! .get(endpoint) 118 | //! ) 119 | //! .post(endpoint) 120 | //! ) 121 | //! .at("api/v2", |route| route 122 | //! .get(endpoint) 123 | //! .get(endpoint) 124 | //! ), 125 | //! ); 126 | //! ``` 127 | //! 128 | //! Serving directories is possible using `serve_dir`, this works the same as with normal Tide routes, 129 | //! fluent routes adds the `serve_file` convenience method for serving single files. 130 | //! ```rust,no_run 131 | //! # use tide::{Request, Result}; 132 | //! use tide_fluent_routes::prelude::*; 133 | //! use tide_fluent_routes::fs::ServeFs; 134 | //! 135 | //! let mut server = tide::Server::new(); 136 | //! 137 | //! server.register( 138 | //! root() 139 | //! .serve_file("files/index.html").unwrap() 140 | //! .at("img", |r| r 141 | //! .serve_dir("files/images").unwrap() 142 | //! ) 143 | //! ); 144 | //! ``` 145 | 146 | // Turn on warnings for some lints 147 | #![warn( 148 | missing_debug_implementations, 149 | missing_docs, 150 | trivial_casts, 151 | trivial_numeric_casts, 152 | unreachable_pub, 153 | unused_import_braces, 154 | unused_qualifications 155 | )] 156 | 157 | pub mod fs; 158 | mod path; 159 | pub mod reverse_router; 160 | pub mod routebuilder; 161 | pub mod router; 162 | mod routesegment; 163 | mod util; 164 | 165 | use std::collections::HashMap; 166 | pub use tide::Error; 167 | 168 | /// The result type for fluent routing 169 | pub type Result = std::result::Result; 170 | 171 | /// Import types to use tide_fluent_routes 172 | pub mod prelude { 173 | pub use super::reverse_router::ReverseRouter; 174 | pub use super::routebuilder::{RouteBuilder, RouteBuilderExt}; 175 | pub use super::router::Router; 176 | pub use super::routesegment::{root, RouteSegment, SubRoute}; 177 | pub use tide::http::Method; 178 | } 179 | 180 | #[cfg(test)] 181 | mod test { 182 | use crate::prelude::*; 183 | use crate::util::ArcMiddleware; 184 | use std::future::Future; 185 | use std::pin::Pin; 186 | use tide::{Next, Request, Result}; 187 | 188 | #[test] 189 | fn should_build_single_endpoint() { 190 | let routes: Vec<_> = root::<()>().get(|_| async { Ok("") }).unwrap().build(); 191 | 192 | assert_eq!(routes.len(), 1); 193 | } 194 | 195 | #[test] 196 | fn should_build_multiple_endpoints() { 197 | let routes: Vec<_> = root::<()>() 198 | .get(|_| async { Ok("") }) 199 | .post(|_| async { Ok("") }) 200 | .unwrap() 201 | .build(); 202 | 203 | assert_eq!(routes.len(), 2); 204 | } 205 | 206 | #[test] 207 | fn should_build_sub_endpoints() { 208 | let routes: Vec<_> = root::<()>() 209 | .at("sub_path", |r| { 210 | r.get(|_| async { Ok("") }).post(|_| async { Ok("") }) 211 | }) 212 | .unwrap() 213 | .build(); 214 | 215 | assert_eq!(routes.len(), 2); 216 | } 217 | 218 | #[test] 219 | fn should_build_endpoint_path() { 220 | let routes: Vec<_> = root::<()>() 221 | .at("path", |r| r.at("subpath", |r| r.get(|_| async { Ok("") }))) 222 | .unwrap() 223 | .build(); 224 | 225 | assert_eq!(routes.len(), 1); 226 | // TODO: Fix this, possibly with a named endpoint 227 | // assert_eq!(routes.get(0).unwrap().route, Some(Method::Get)); 228 | assert_eq!( 229 | routes.get(0).unwrap().path.to_string(), 230 | "/path/subpath".to_string() 231 | ); 232 | } 233 | 234 | #[test] 235 | fn should_start_path_with_slash() { 236 | let routes: Vec<_> = root::<()>().get(|_| async { Ok("") }).unwrap().build(); 237 | assert_eq!(routes.get(0).unwrap().path.to_string(), "/".to_string()); 238 | } 239 | 240 | fn middleware<'a>( 241 | request: Request<()>, 242 | next: Next<'a, ()>, 243 | ) -> Pin + Send + 'a>> { 244 | Box::pin(async { Ok(next.run(request).await) }) 245 | } 246 | 247 | #[test] 248 | fn should_collect_middleware() { 249 | let middleware1 = ArcMiddleware::new(middleware); 250 | let middleware2 = ArcMiddleware::new(middleware); 251 | 252 | let routes: Vec<_> = root::<()>() 253 | .at("path", |r| { 254 | r.with(middleware1.clone(), |r| { 255 | r.at("subpath", |r| { 256 | r.with(middleware2.clone(), |r| r.get(|_| async { Ok("") })) 257 | }) 258 | .get(|_| async { Ok("") }) 259 | }) 260 | }) 261 | .unwrap() 262 | .build(); 263 | 264 | assert_eq!(routes.get(0).unwrap().middleware.len(), 1); 265 | assert_eq!(routes.get(1).unwrap().middleware.len(), 2); 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /src/path.rs: -------------------------------------------------------------------------------- 1 | /// Newtype for collecting path segments into a path 2 | #[derive(Debug, Clone, PartialEq)] 3 | pub(crate) struct Path(String); 4 | 5 | impl Path { 6 | /// Create new path from a prefix 7 | pub(crate) fn prefix(value: &str) -> Self { 8 | Path(value.to_string()) 9 | } 10 | 11 | pub(crate) fn append(self, segment: &str) -> Path { 12 | if self.0.is_empty() { 13 | Path(segment.to_string()) 14 | } else { 15 | let mut path = self.0.trim_end_matches('/').to_string(); 16 | path.push('/'); 17 | path.push_str(segment.trim_start_matches('/')); 18 | Path(path) 19 | } 20 | } 21 | } 22 | 23 | impl ToString for Path { 24 | fn to_string(&self) -> String { 25 | self.0.clone() 26 | } 27 | } 28 | 29 | #[cfg(test)] 30 | mod test { 31 | use super::*; 32 | 33 | #[test] 34 | fn should_handle_slashes_between_segments() { 35 | let path = Path::prefix("") 36 | .append("/tst1/") 37 | .append("tst2") 38 | .append("/tst3/") 39 | .append("//tst4///") 40 | .append("/tst5/"); 41 | 42 | assert_eq!(path.to_string(), "/tst1/tst2/tst3/tst4/tst5/"); 43 | } 44 | 45 | #[test] 46 | fn should_preserve_prefix_slash() { 47 | let path = Path::prefix("").append("/tst1").append("tst2"); 48 | 49 | assert_eq!(path.to_string(), "/tst1/tst2"); 50 | } 51 | 52 | #[test] 53 | fn should_preserve_trailing_slash() { 54 | let path = Path::prefix("").append("tst1").append("tst2/"); 55 | 56 | assert_eq!(path.to_string(), "tst1/tst2/"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/reverse_router.rs: -------------------------------------------------------------------------------- 1 | //! The reverse router returns routes by their name. 2 | 3 | use crate::HashMap; 4 | 5 | /// Stores a list of routes by name 6 | #[derive(Debug)] 7 | pub struct ReverseRouter { 8 | routes: HashMap, 9 | } 10 | 11 | impl ReverseRouter { 12 | /// Insert a named route 13 | pub fn insert(&mut self, name: &str, route: &str) { 14 | self.routes.insert(name.to_string(), route.to_string()); 15 | } 16 | 17 | /// Resolve a named route 18 | pub fn resolve(&self, name: &str, _params: Params) -> String { 19 | let route = self.routes[name].clone(); 20 | 21 | // todo: replace params with values 22 | 23 | route 24 | } 25 | 26 | /// Construct a named routes list 27 | pub fn new() -> Self { 28 | ReverseRouter { 29 | routes: HashMap::new(), 30 | } 31 | } 32 | } 33 | 34 | /// Parameters for insertion in paths 35 | #[derive(Debug, Clone, PartialEq, Default)] 36 | pub struct Params(HashMap); 37 | 38 | impl Params { 39 | /// Create new params 40 | pub fn new() -> Self { 41 | Self::default() 42 | } 43 | 44 | /// Insert a parameter 45 | pub fn insert(&mut self, param: P, value: V) { 46 | self.0.insert(param.to_string(), value.to_string()); 47 | } 48 | } 49 | 50 | /// Construct parameters for the reverse router 51 | #[macro_export] 52 | macro_rules! params { 53 | () => {{ 54 | Params::new() 55 | }}; 56 | 57 | ($( $param:expr => $value:expr ),+ ) => {{ 58 | let mut pm: Params = Params::new(); 59 | $(pm.insert($param.to_string(), $value);)* 60 | pm 61 | }}; 62 | } 63 | 64 | #[cfg(test)] 65 | mod test { 66 | use super::*; 67 | 68 | #[test] 69 | fn should_construct_empty_params() { 70 | let params = params! {}; 71 | assert_eq!(params, Params::new()); 72 | } 73 | 74 | #[test] 75 | fn should_construct_params() { 76 | let params = params! {"thing" => 5}; 77 | 78 | let mut expected = Params::new(); 79 | expected.insert("thing".to_string(), 5); 80 | 81 | assert_eq!(params, expected); 82 | } 83 | 84 | #[test] 85 | fn should_construct_multi_value_params() { 86 | let params = params! {"thing1" => 5, "thing2" => "another thing"}; 87 | 88 | let mut expected = Params::new(); 89 | expected.insert("thing1".to_string(), 5); 90 | expected.insert("thing2", "another thing"); 91 | 92 | assert_eq!(params, expected); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/routebuilder.rs: -------------------------------------------------------------------------------- 1 | //! The RouteBuilder trait defines the internal dsl to build route trees as implemented by all 2 | //! RouteSegments 3 | 4 | use tide::http::Method; 5 | use tide::{Endpoint, Middleware}; 6 | 7 | /// A routebuilder can be used to define routes by adding path segments, middelwares and endpoints 8 | /// to a route tree 9 | pub trait RouteBuilder: Sized { 10 | /// Add a path segment with a set of sub-routes 11 | fn at Self>(self, path: &str, routes: R) -> Self; 12 | 13 | /// Add middleware with a set of sub-routes 14 | fn with, R: FnOnce(Self) -> Self>(self, middleware: M, routes: R) -> Self; 15 | 16 | /// Add an endpoint for an http method 17 | fn method(self, method: Method, endpoint: impl Endpoint) -> Self; 18 | 19 | /// Add a catchall endpoint 20 | fn all(self, endpoint: impl Endpoint) -> Self; 21 | 22 | /// Make this a named route 23 | fn name(self, name: &str) -> Self; 24 | } 25 | 26 | /// Some extension methods for the routebuilder to make the routing dsl a bit nicer 27 | pub trait RouteBuilderExt: RouteBuilder { 28 | /// Add an HTTP GET endpoint 29 | fn get(self, endpoint: impl Endpoint) -> Self { 30 | self.method(Method::Get, endpoint) 31 | } 32 | 33 | /// Add an HTTP HEAD endpoint 34 | fn head(self, endpoint: impl Endpoint) -> Self { 35 | self.method(Method::Head, endpoint) 36 | } 37 | 38 | /// Add an HTTP PUT endpoint 39 | fn put(self, endpoint: impl Endpoint) -> Self { 40 | self.method(Method::Put, endpoint) 41 | } 42 | 43 | /// Add an HTTP POST endpoint 44 | fn post(self, endpoint: impl Endpoint) -> Self { 45 | self.method(Method::Post, endpoint) 46 | } 47 | 48 | /// Add an HTTP DELETE endpoint 49 | fn delete(self, endpoint: impl Endpoint) -> Self { 50 | self.method(Method::Delete, endpoint) 51 | } 52 | 53 | /// Add an HTTP OPTIONS endpoint 54 | fn options(self, endpoint: impl Endpoint) -> Self { 55 | self.method(Method::Options, endpoint) 56 | } 57 | 58 | /// Add an HTTP CONNECT endpoint 59 | fn connect(self, endpoint: impl Endpoint) -> Self { 60 | self.method(Method::Connect, endpoint) 61 | } 62 | 63 | /// Add an HTTP PATCH endpoint 64 | fn patch(self, endpoint: impl Endpoint) -> Self { 65 | self.method(Method::Patch, endpoint) 66 | } 67 | 68 | /// Add an HTTP TRACE endpoint 69 | fn trace(self, endpoint: impl Endpoint) -> Self { 70 | self.method(Method::Trace, endpoint) 71 | } 72 | } 73 | 74 | impl> RouteBuilderExt for R {} 75 | -------------------------------------------------------------------------------- /src/router.rs: -------------------------------------------------------------------------------- 1 | //! The router trait and its implementation on tide::Server connect the RouteBuilder to tide and 2 | //! allows you to call register on a tide::Server with a fluent route tree 3 | 4 | use crate::routesegment::{Route, RouteDescriptor, RouteSegment}; 5 | use crate::{util::ArcMiddleware, Result}; 6 | use tide::{http::Method, Endpoint}; 7 | 8 | /// A router is any component where routes can be registered on like a tide::Server 9 | pub trait Router: Sized { 10 | /// Register a single endpoint on the `Router` 11 | fn register_endpoint( 12 | &mut self, 13 | path: &str, 14 | method: Option, 15 | middleware: &[ArcMiddleware], 16 | endpoint: impl Endpoint, 17 | ); 18 | 19 | /// Register all routes from a RouteBuilder on the `Router` 20 | fn register(&mut self, builder: Result>) -> Result<&mut Self> { 21 | for RouteDescriptor { 22 | path, 23 | middleware, 24 | route, 25 | } in builder?.build() 26 | { 27 | if let Route::Handler(method, endpoint) = route { 28 | self.register_endpoint(&path.to_string(), method, &middleware, endpoint) 29 | } 30 | } 31 | 32 | Ok(self) 33 | } 34 | } 35 | 36 | impl Router for tide::Server { 37 | fn register_endpoint( 38 | &mut self, 39 | path: &str, 40 | method: Option, 41 | middleware: &[ArcMiddleware], 42 | endpoint: impl Endpoint, 43 | ) { 44 | let mut route = self.at(path); 45 | for ware in middleware { 46 | route.with(ware.clone()); 47 | } 48 | 49 | // if method is specified then register this method, otherwise register endpoint as a catch_all 50 | match method { 51 | Some(method) => self.at(path).method(method, endpoint), 52 | None => self.at(path).all(endpoint), 53 | }; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/routesegment.rs: -------------------------------------------------------------------------------- 1 | use crate::path::Path; 2 | use crate::reverse_router::ReverseRouter; 3 | use crate::routebuilder::RouteBuilder; 4 | use crate::util::{ArcMiddleware, BoxedEndpoint}; 5 | use crate::Result; 6 | use std::collections::HashMap; 7 | use tide::http::Method; 8 | use tide::{Endpoint, Middleware}; 9 | 10 | /// Start building a route. Returns a RouteSegment for the root of your route 11 | pub fn root() -> SubRoute { 12 | Ok(RouteSegment { 13 | path: Path::prefix("/"), 14 | middleware: Vec::new(), 15 | name: None, 16 | branches: Vec::new(), 17 | endpoints: HashMap::new(), 18 | }) 19 | } 20 | 21 | /// A segment of a tide route tree. RouteSegments can be composed into trees that represents a tree of 22 | /// path segments, middleware and endpoints that defines the routes in a Tide application. This tree 23 | /// can then be returned as a list of routes to each of the endpoints. 24 | #[derive(Debug)] 25 | pub struct RouteSegment { 26 | path: Path, 27 | middleware: Vec>, 28 | 29 | name: Option, 30 | branches: Vec>, 31 | endpoints: HashMap, BoxedEndpoint>, 32 | } 33 | 34 | impl RouteSegment { 35 | fn names(&self) -> Vec> { 36 | let path = self.path.clone(); 37 | 38 | let local_name = self 39 | .name 40 | .clone() 41 | .map(|name| RouteDescriptor { 42 | path: path.clone(), 43 | middleware: Vec::new(), // We don't care about middleware for route names 44 | route: Route::Name(name), 45 | }) 46 | .into_iter(); 47 | 48 | let sub_routes = self.branches.iter().flat_map(RouteSegment::names); 49 | 50 | local_name.chain(sub_routes).collect() 51 | } 52 | 53 | /// Construct a reverse router for the paths in the route builder 54 | pub fn reverse_router(&self) -> ReverseRouter { 55 | let mut routes = ReverseRouter::new(); 56 | 57 | for RouteDescriptor { 58 | path, 59 | middleware: _, 60 | route, 61 | } in self.names() 62 | { 63 | if let Route::Name(name) = route { 64 | routes.insert(&name, &path.to_string()); 65 | } 66 | } 67 | 68 | routes 69 | } 70 | 71 | pub(crate) fn build(self) -> Vec> { 72 | let path = self.path; 73 | let middleware = self.middleware; 74 | 75 | let local_endpoints = 76 | self.endpoints 77 | .into_iter() 78 | .map(|(method, endpoint)| RouteDescriptor { 79 | path: path.clone(), 80 | middleware: middleware.clone(), 81 | route: Route::Handler(method, endpoint), 82 | }); 83 | 84 | let sub_endpoints = self.branches.into_iter().flat_map(RouteSegment::build); 85 | 86 | local_endpoints.chain(sub_endpoints).collect() 87 | } 88 | } 89 | 90 | impl RouteBuilder for Result> { 91 | fn at Self>(self, path: &str, routes: R) -> Self { 92 | let mut segment = self?; 93 | 94 | segment.branches.push(routes(Ok(RouteSegment { 95 | path: segment.path.clone().append(path), 96 | middleware: segment.middleware.clone(), 97 | name: None, 98 | branches: Vec::new(), 99 | endpoints: HashMap::new(), 100 | }))?); 101 | Ok(segment) 102 | } 103 | 104 | fn with, R: FnOnce(Self) -> Self>(self, middleware: M, routes: R) -> Self { 105 | let mut segment = self?; 106 | let mut ware = segment.middleware.clone(); 107 | 108 | ware.push(ArcMiddleware::new(middleware)); 109 | 110 | segment.branches.push(routes(Ok(RouteSegment { 111 | path: segment.path.clone(), 112 | middleware: ware, 113 | name: None, 114 | branches: Vec::new(), 115 | endpoints: HashMap::new(), 116 | }))?); 117 | Ok(segment) 118 | } 119 | 120 | fn method(self, method: Method, endpoint: impl Endpoint) -> Self { 121 | let mut segment = self?; 122 | 123 | segment 124 | .endpoints 125 | .insert(Some(method), BoxedEndpoint::new(endpoint)); 126 | Ok(segment) 127 | } 128 | 129 | fn all(self, endpoint: impl Endpoint) -> Self { 130 | let mut segment = self?; 131 | 132 | segment.endpoints.insert(None, BoxedEndpoint::new(endpoint)); 133 | Ok(segment) 134 | } 135 | 136 | fn name(self, name: &str) -> Self { 137 | let mut segment = self?; 138 | 139 | if let Some(name) = segment.name { 140 | panic!("route already has name: {}", name); 141 | } 142 | segment.name = Some(name.to_string()); 143 | Ok(segment) 144 | } 145 | } 146 | 147 | /// Partial routing results for passing around in routing closures 148 | pub type SubRoute = Result>; 149 | 150 | /// Describes a branch in the route tree, the path and middleware collected and the route as the leaf 151 | #[derive(Debug)] 152 | pub(crate) struct RouteDescriptor { 153 | pub(crate) path: Path, 154 | pub(crate) middleware: Vec>, 155 | pub(crate) route: Route, 156 | } 157 | 158 | /// Descibes a leaf in the route tree, either a name or a handler 159 | #[derive(Debug)] 160 | pub(crate) enum Route { 161 | Name(String), 162 | Handler(Option, BoxedEndpoint), 163 | } 164 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt::{Debug, Formatter, Result as FmtResult}, 3 | sync::Arc, 4 | }; 5 | use tide::Endpoint; 6 | use tide::{utils::async_trait, Middleware}; 7 | 8 | /// Implement some useful stuff around Box 9 | pub(crate) struct BoxedEndpoint(Box>); 10 | 11 | impl BoxedEndpoint { 12 | /// Wrap an endpoint in a BoxedEndpoint 13 | pub(crate) fn new(endpoint: impl Endpoint) -> Self { 14 | Self(Box::new(endpoint)) 15 | } 16 | } 17 | 18 | impl Debug for BoxedEndpoint { 19 | fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult { 20 | formatter.debug_struct("BoxedEndpoint").finish() 21 | } 22 | } 23 | 24 | #[async_trait] 25 | impl Endpoint for BoxedEndpoint { 26 | async fn call(&self, req: tide::Request) -> tide::Result { 27 | self.0.call(req).await 28 | } 29 | } 30 | 31 | /// Implement some useful stuff around Arc 32 | #[derive(Clone)] 33 | pub struct ArcMiddleware(Arc>); 34 | 35 | impl ArcMiddleware { 36 | /// Wrap an endpoint in a BoxedEndpoint 37 | pub(crate) fn new(ware: impl Middleware) -> Self { 38 | Self(Arc::new(ware)) 39 | } 40 | } 41 | 42 | impl Debug for ArcMiddleware { 43 | fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult { 44 | formatter.debug_struct("ArcMiddleware").finish() 45 | } 46 | } 47 | 48 | #[async_trait] 49 | impl Middleware for ArcMiddleware { 50 | async fn handle( 51 | &self, 52 | request: tide::Request, 53 | next: tide::Next<'_, State>, 54 | ) -> tide::Result { 55 | self.0.handle(request, next).await 56 | } 57 | } 58 | --------------------------------------------------------------------------------