# pathrouter [![Build Status](https://travis-ci.org/naleek/pathrouter.svg?branch=master)](https://travis-ci.org/naleek/pathrouter) [![Coverage Status](https://coveralls.io/repos/github/naleek/pathrouter/badge.svg?branch=master)](https://coveralls.io/github/naleek/pathrouter?branch=master) [![GoDoc](https://godoc.org/github.com/naleek/PathRouter?status.svg)](http://godoc.org/github.com/naleek/pathrouter) pathrouter is a lightweight high performance path router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/). 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. pathrouter was born out of [github.com/julienschmidt/httprouter](http://github.com/julienschmidt/httprouter), It extracts the path matching logic, and discards all of the HTTP specific logic. ## Features **Only explicit matches:** By design of this router, a request can only match exactly one or no route. As a result, there are no unintended matches. **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. **Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters. ## Usage This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/naleek/pathrouter) for details. Let's start with a trivial example: ```go package main import ( "fmt" "github.com/naleek/pathrouter" ) func Hello(ps pathrouter.Params, d interface{}) { u := d.(string) fmt.Printf("hello, %s!\nUser Data: %s\n", ps.ByName("name"), u) } func main() { router := pathrouter.New() router.Handle("/hello/:name", Hello) router.Execute("/hello/bob", "boring user data") } ``` ### Named parameters As you can see, `:name` is a *named parameter*. The values are accessible via `pathrouter.Params`, which is just a slice of `pathrouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrived by `ByName("name")`. Named parameters only match a single path segment: ``` 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. ### Catch-All parameters 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: ``` Pattern: /src/*filepath /src/ match /src/somefile.go match /src/subdir/somefile.go match ``` ## How does it work? This is straight from the github.com/julienschmidt/httprouter documentation. The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like: ``` Priority Path Handle 9 \ *<1> 3 ├s nil 2 |├earch\ *<2> 1 |└upport\ *<3> 2 ├blog\ *<4> 1 | └:post nil 1 | └\ *<5> 2 ├about-us\ *<6> 1 | └team\ *<7> 1 └contact\ *<8> ``` Every `*` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/naleek/go-http-routing-benchmark), this works very well and efficient. Since paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree. For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways: 1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible. 2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right. ``` ├------------ ├--------- ├----- ├---- ├-- ├-- └- ``` ## Why? Sometimes a person needs to match routes, but not in a HTTP environment.