Treemux is a lightweight high performance HTTP request router.
This router supports variables in the routing pattern and matches against the request method. It also scales very well.
The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching. Internally, it uses the matchit package.
Treemux started as a fork of httprouter-rs by @ibraheemdev. And is just a learning project for me at the moment, to get more familiar with hyper and tower services.
Only explicit matches: With other routers, a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like longest match or first registered, first matched. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
Path auto-correction: Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like ../
or //
). Is CAPTAIN CAPS LOCK one of your users? Treemux can help him by making a case-insensitive look-up and redirecting him to the correct URL.
Parameters in your routing pattern: Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
High Performance: Treemux relies on a tree structure which makes heavy use of common prefixes, it is basically a radix tree. This makes lookups extremely fast. Internally, it uses the matchit package.
Of course you can also set custom NotFound
and MethodNotAllowed
handlers , serve static files, and automatically respond to OPTIONS requests
Here is a simple example:
```rust,no_run use treemux::{Router, Params}; use std::convert::Infallible; use hyper::{Request, Response, Body}; use anyhow::Error;
async fn index(_: Request
) -> Resultasync fn hello(req: Request
) -> Resultasync fn main() { let mut router: Router = Router::default(); router.get("/", index); router.get("/hello/:user", hello);
hyper::Server::bind(&([127, 0, 0, 1], 3000).into()) .serve(router.into_service()) .await; } ```
As you can see, :user
is a named parameter. The values are accessible via req.extensions().get::<Params>()
.
Named parameters only match a single path segment:
```ignore Pattern: /user/:user
/user/gordon match /user/you match /user/gordon/profile no match /user/ no match ```
Note: Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns /user/new
and /user/:user
for the same request method at the same time. The routing of different request methods is independent from each other.
The second type are catch-all parameters and have the form *name
. Like the name suggests, they match everything. Therefore they must always be at the end of the pattern:
```ignore Pattern: /src/*filepath
/src/ match /src/somefile.go match /src/subdir/somefile.go match ```
One might wish to modify automatic responses to OPTIONS requests, e.g. to support CORS preflight requests or to set other headers. This can be achieved using the Router::global_options
handler:
```rust use treemux::Router; use hyper::{Request, Response, Body}; use anyhow::Error;
async fn globaloptions(: Request
) -> Resultfn main() { let mut router: Router = Router::default(); router.globaloptions(globaloptions); } ```
Here is a quick example: Does your server serve multiple domains / hosts? You want to use sub-domains? Define a router per host!
```rust,norun use treemux::Router; use treemux::router::RouterService; use hyper::service::{makeservicefn, servicefn}; use hyper::{Body, Request, Response, Server, StatusCode}; use std::collections::HashMap; use std::convert::Infallible; use std::sync::Arc;
pub struct HostSwitch(HashMap
impl HostSwitch { async fn serve(&self, req: Request
) -> anyhow::Resultasync fn hello(_: Request
) -> anyhow::Resultasync fn main() { let mut router: Router = Router::default(); router.get("/", hello);
let mut hostswitch: HostSwitch = HostSwitch(HashMap::new()); hostswitch.0.insert("example.com:12345".into(), router);
let hostswitch = Arc::new(hostswitch);
let makesvc = makeservicefn(move || { let hostswitch = hostswitch.clone(); async move { Ok::<_, Infallible>(servicefn(move |req: Request| { let hostswitch = hostswitch.clone(); async move { hostswitch.serve(req).await } })) } });
let server = Server::bind(&([127, 0, 0, 1], 3000).into()) .serve(make_svc) .await; } ```
NOTE: It might be required to set Router::method_not_allowed
to None
to avoid problems.
You can use another handler, to handle requests which could not be matched by this router by using the Router::not_found
handler.
The not_found
handler can for example be used to return a 404 page:
```rust use treemux::Router; use hyper::{Request, Response, Body}; use anyhow::Error;
async fn not_found(req: Request
) -> Resultfn main() { let mut router: Router = Router::default(); router.notfound(notfound); } ```
You can use the router to serve pages from a static file directory:
rust
// TODO