├── go.mod ├── .gitignore ├── README.md ├── parameters.go ├── router.go ├── node.go ├── router_test.go └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/CloudyKit/router 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | .idea 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## CloudyKit Router 2 | 3 | CloudyKit Router was developed to be a very fast router on matching and retrieving of parameters. 4 | 5 | ### Main characteristics 6 | 7 | 1. Use prefix tree with special nodes to match dynamic sentences and catch all. 8 | 2. No allocations, matching and retrieve parameters don't allocates. 9 | 3. Nodes has precedence when matching, text node then single sentence node then wildcard node 10 | 11 | ### Benchmarks 12 | 13 | I benchmark CloudyKit router against "github.com/julienschmidt/httprouter" and the results are pretty good, the benchmark consist of test the routes listem below per each iteration. 14 | 15 | ```go 16 | /users 17 | /users/:userId 18 | /users/:userId/subscriptions 19 | /users/:userId/subscriptions/:subscription 20 | /assets/*file 21 | ``` 22 | 23 | Benchmark source: https://github.com/CloudyKit/benchmarks/router 24 | 25 | ####### Results 26 | ```text 27 | Go 1.6 28 | BenchmarkCloudyKitRouter-4 2000000 618 ns/op 0 B/op 0 allocs/op 29 | BenchmarkHttprouterRouter-4 1000000 1104 ns/op 224 B/op 4 allocs/op 30 | 31 | Go tip 32 | BenchmarkCloudyKitRouter-4 3000000 492 ns/op 0 B/op 0 allocs/op 33 | BenchmarkHttprouterRouter-4 2000000 1006 ns/op 224 B/op 4 allocs/op 34 | ``` 35 | 36 | 37 | *** 38 | 39 | ### Precedence example 40 | 41 | On the example below the router will test the routes in the following order, /users/list then /users/:userId then /users/*page. 42 | ```go 43 | router.AddRoute("GET","/users/:userId",...) 44 | router.AddRoute("GET","/users/*page",...) 45 | router.AddRoute("GET","/users/list",...) 46 | ``` 47 | -------------------------------------------------------------------------------- /parameters.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 José Santos 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 | package router 16 | 17 | import "strings" 18 | 19 | // Parameter holds the parameters matched in the route 20 | type Parameter struct { 21 | *routeNode // matched node 22 | path string // url path given 23 | wildcard int // size of the wildcard match in the end of the string 24 | } 25 | 26 | // Index returns the index of the argument by name 27 | func (vv *Parameter) Index(name string) int { 28 | if i, has := vv.names[name]; has { 29 | return i 30 | } 31 | return -1 32 | } 33 | 34 | // Len returns number arguments matched in the provided URL 35 | func (vv *Parameter) Len() int { 36 | return len(vv.names) 37 | } 38 | 39 | // Get returns the url parameter by name 40 | func (vv *Parameter) Get(name string) string { 41 | if i, has := vv.names[name]; has { 42 | return vv.findParam(i) 43 | } 44 | return "" 45 | } 46 | 47 | // findParam walks up the matched node looking for parameters returns the last parameter 48 | func (vv *Parameter) findParam(idx int) (param string) { 49 | var ( 50 | curIndex = len(vv.names) - 1 51 | urlPath = vv.path 52 | pathLen = len(vv.path) 53 | curNode = vv.routeNode 54 | ) 55 | 56 | if curNode.text[0] == '*' { 57 | pathLen -= vv.wildcard 58 | if curIndex == idx { 59 | param = urlPath[pathLen:] 60 | return 61 | } 62 | curIndex-- 63 | curNode = curNode.parent 64 | } 65 | 66 | for curNode != nil { 67 | if curNode.text[0] == ':' { 68 | nextSlash := strings.LastIndexByte(urlPath, '/') 69 | if nextSlash == -1 { 70 | return 71 | } 72 | pathLen = nextSlash + 1 73 | if curIndex == idx { 74 | param = urlPath[pathLen:] 75 | return 76 | } 77 | curIndex-- 78 | } else { 79 | pathLen -= len(curNode.text) 80 | } 81 | urlPath = urlPath[0:pathLen] 82 | curNode = curNode.parent 83 | 84 | } 85 | return 86 | } 87 | -------------------------------------------------------------------------------- /router.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 José Santos 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 | package router 16 | 17 | import ( 18 | "fmt" 19 | "net/http" 20 | ) 21 | 22 | type Handler func(http.ResponseWriter, *http.Request, Parameter) 23 | 24 | type Router struct { 25 | trees map[string]*routeNode 26 | } 27 | 28 | func New() *Router { 29 | return &Router{trees: make(map[string]*routeNode)} 30 | } 31 | 32 | func splitURLpath(path string) (parts []string, names map[string]int) { 33 | 34 | var ( 35 | nameidx int = -1 36 | partidx int 37 | paramCounter int 38 | ) 39 | 40 | for i := 0; i < len(path); i++ { 41 | // recording name 42 | if nameidx != -1 { 43 | //found / 44 | if path[i] == '/' { 45 | 46 | if names == nil { 47 | names = make(map[string]int) 48 | } 49 | 50 | names[path[nameidx:i]] = paramCounter 51 | paramCounter++ 52 | 53 | nameidx = -1 // switch to normal recording 54 | partidx = i 55 | } 56 | } else { 57 | if path[i] == ':' || path[i] == '*' { 58 | if path[i-1] != '/' { 59 | panic(fmt.Errorf("Inválid parameter : or * comes anwais after / - %q", path)) 60 | } 61 | nameidx = i + 1 62 | if partidx != i { 63 | parts = append(parts, path[partidx:i]) 64 | } 65 | parts = append(parts, path[i:nameidx]) 66 | } 67 | } 68 | } 69 | 70 | if nameidx != -1 { 71 | if names == nil { 72 | names = make(map[string]int) 73 | } 74 | names[path[nameidx:]] = paramCounter 75 | paramCounter++ 76 | } else if partidx < len(path) { 77 | parts = append(parts, path[partidx:]) 78 | } 79 | return 80 | } 81 | 82 | func (router *Router) Finalize() { 83 | for _, _node := range router.trees { 84 | _node.finalize() 85 | } 86 | } 87 | 88 | func (router *Router) FindRoute(method string, path string) (Handler, Parameter) { 89 | _node := router.trees[method] 90 | if _node == nil { 91 | return nil, Parameter{} 92 | } 93 | fn, wildcard := _node.findRoute(path) 94 | 95 | if fn != nil { 96 | return fn.handler, Parameter{routeNode: fn, path: path, wildcard: wildcard} 97 | } 98 | return nil, Parameter{} 99 | } 100 | 101 | func (router *Router) AddRoute(method string, path string, fn Handler) { 102 | parts, names := splitURLpath(path) 103 | _node := router.trees[method] 104 | if _node == nil { 105 | _node = &routeNode{} 106 | router.trees[method] = _node 107 | } 108 | _node.addRoute(parts, names, fn) 109 | _node.optimizeRoutes() 110 | } 111 | 112 | func (router *Router) String() string { 113 | var lines string 114 | for method, _node := range router.trees { 115 | lines += method + " " + _node.String() 116 | } 117 | return lines 118 | } 119 | 120 | func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { 121 | handler, variables := router.FindRoute(r.Method, r.URL.Path) 122 | if handler != nil { 123 | handler(w, r, variables) 124 | } else { 125 | http.NotFound(w, r) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /node.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 José Santos 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 | package router 16 | 17 | import ( 18 | "net/http" 19 | "sort" 20 | "strings" 21 | ) 22 | 23 | type routeNode struct { 24 | text string 25 | names map[string]int 26 | handler Handler 27 | 28 | parent *routeNode 29 | wildcard *routeNode 30 | colon *routeNode 31 | 32 | nodes []*routeNode 33 | start byte 34 | max byte 35 | indices []uint8 36 | } 37 | 38 | func (node *routeNode) nextRoute(path string) (*routeNode, int8, int) { 39 | 40 | if path == "*" { 41 | if node.wildcard == nil { 42 | node.wildcard = &routeNode{text: "*"} 43 | } 44 | return node.wildcard, 0, 0 45 | } 46 | 47 | if path == ":" { 48 | if node.colon == nil { 49 | node.colon = &routeNode{text: ":"} 50 | } 51 | return node.colon, 0, 0 52 | } 53 | 54 | for i := 0; i < len(node.nodes); i++ { 55 | cNode := node.nodes[i] 56 | if cNode.text[0] == path[0] { 57 | 58 | var max = len(cNode.text) 59 | var lpath = len(path) 60 | var pathIsBigger int8 61 | 62 | if lpath > max { 63 | pathIsBigger = 1 64 | } else if lpath < max { 65 | max = lpath 66 | pathIsBigger = -1 67 | } 68 | 69 | for j := 0; j < max; j++ { 70 | if path[j] != cNode.text[j] { 71 | ccNode := &routeNode{text: path[0:j], nodes: []*routeNode{cNode, &routeNode{text: path[j:]}}} 72 | cNode.text = cNode.text[j:] 73 | node.nodes[i] = ccNode 74 | return ccNode.nodes[1], 0, i 75 | } 76 | } 77 | 78 | return cNode, pathIsBigger, i 79 | } 80 | } 81 | 82 | return nil, 0, 0 83 | } 84 | 85 | func (node *routeNode) addRoute(parts []string, names map[string]int, handler Handler) { 86 | 87 | var ( 88 | ccNode *routeNode 89 | cNode *routeNode 90 | ) 91 | 92 | cNode, result, idx := node.nextRoute(parts[0]) 93 | 94 | RESTART: 95 | if cNode == nil { 96 | cNode = &routeNode{text: parts[0]} 97 | node.nodes = append(node.nodes, cNode) 98 | } else if result == 1 { 99 | // 100 | parts[0] = parts[0][len(cNode.text):] 101 | ccNode, result, idx = cNode.nextRoute(parts[0]) 102 | if cNode != nil { 103 | node = cNode 104 | cNode = ccNode 105 | goto RESTART 106 | } 107 | ccNode := &routeNode{text: parts[0]} 108 | cNode.nodes = append(node.nodes, ccNode) 109 | cNode = ccNode 110 | } else if result == -1 { 111 | ccNode := &routeNode{text: parts[0]} 112 | cNode.text = cNode.text[len(ccNode.text):] 113 | ccNode.nodes = []*routeNode{cNode} 114 | node.nodes[idx] = ccNode 115 | cNode = ccNode 116 | } 117 | 118 | if len(parts) == 1 { 119 | cNode.handler = handler 120 | cNode.names = names 121 | return 122 | } 123 | 124 | cNode.addRoute(parts[1:], names, handler) 125 | } 126 | 127 | var redirectNode = &routeNode{ 128 | handler: func(w http.ResponseWriter, r *http.Request, p Parameter) { 129 | http.Redirect(w, r, r.URL.Path+"/", http.StatusFound) 130 | }, 131 | } 132 | 133 | func (node *routeNode) findRoute(urlPath string) (*routeNode, int) { 134 | 135 | urlByte := urlPath[0] 136 | pathLen := len(urlPath) 137 | 138 | if urlByte >= node.start && urlByte <= node.max { 139 | if i := node.indices[urlByte-node.start]; i != 0 { 140 | cNode := node.nodes[i-1] 141 | nodeLen := len(cNode.text) 142 | if nodeLen < pathLen { 143 | if cNode.text == urlPath[0:nodeLen] { 144 | if cNode, wildcard := cNode.findRoute(urlPath[nodeLen:]); cNode != nil { 145 | return cNode, wildcard 146 | } 147 | } 148 | } else if cNode.text == urlPath { 149 | if cNode.handler == nil && cNode.wildcard != nil { 150 | return cNode.wildcard, 0 151 | } 152 | return cNode, 0 153 | } else if nodeLen == pathLen+1 && cNode.text[nodeLen-1] == '/' { 154 | return redirectNode, 0 155 | } 156 | } 157 | } 158 | 159 | if node.colon != nil && pathLen != 0 { 160 | ix := strings.IndexByte(urlPath, '/') 161 | if ix > 0 { 162 | if cNode, wildcard := node.colon.findRoute(urlPath[ix:]); cNode != nil { 163 | return cNode, wildcard 164 | } 165 | } else if node.colon.handler != nil { 166 | return node.colon, 0 167 | } 168 | } 169 | 170 | if node.wildcard != nil { 171 | return node.wildcard, pathLen 172 | } 173 | 174 | return nil, 0 175 | } 176 | 177 | func (node *routeNode) optimizeRoutes() { 178 | 179 | if len(node.nodes) > 0 { 180 | 181 | sort.Slice(node.nodes, func(i, j int) bool { 182 | return node.nodes[i].text[0] < node.nodes[j].text[0] 183 | }) 184 | 185 | for i := 0; i < len(node.indices); i++ { 186 | node.indices[i] = 0 187 | } 188 | 189 | node.start = node.nodes[0].text[0] 190 | node.max = node.nodes[len(node.nodes)-1].text[0] 191 | 192 | for i := 0; i < len(node.nodes); i++ { 193 | cNode := node.nodes[i] 194 | cNode.parent = node 195 | 196 | cByte := int(cNode.text[0] - node.start) 197 | if cByte >= len(node.indices) { 198 | node.indices = append(node.indices, make([]uint8, cByte+1-len(node.indices))...) 199 | } 200 | node.indices[cByte] = uint8(i + 1) 201 | cNode.optimizeRoutes() 202 | } 203 | } 204 | 205 | if node.colon != nil { 206 | node.colon.parent = node 207 | node.colon.optimizeRoutes() 208 | } 209 | 210 | if node.wildcard != nil { 211 | node.wildcard.parent = node 212 | node.wildcard.optimizeRoutes() 213 | } 214 | } 215 | 216 | func (node *routeNode) finalize() { 217 | if len(node.nodes) > 0 { 218 | for i := 0; i < len(node.nodes); i++ { 219 | node.nodes[i].finalize() 220 | } 221 | } 222 | if node.colon != nil { 223 | node.colon.finalize() 224 | } 225 | if node.wildcard != nil { 226 | node.wildcard.finalize() 227 | } 228 | *node = routeNode{} 229 | } 230 | 231 | func (node *routeNode) string(col int) string { 232 | var str = "\n" + strings.Repeat(" ", col) + node.text + " -> " 233 | col += len(node.text) + 4 234 | for i := 0; i < len(node.indices); i++ { 235 | if j := node.indices[i]; j != 0 { 236 | str += node.nodes[j-1].string(col) 237 | } 238 | } 239 | if node.colon != nil { 240 | str += node.colon.string(col) 241 | } 242 | if node.wildcard != nil { 243 | str += node.wildcard.string(col) 244 | } 245 | return str 246 | } 247 | 248 | func (node *routeNode) String() string { 249 | if node.text == "" { 250 | return node.string(0) 251 | } 252 | col := len(node.text) + 4 253 | return node.text + " -> " + node.string(col) 254 | } 255 | -------------------------------------------------------------------------------- /router_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 José Santos 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 | package router 16 | 17 | import ( 18 | "net/http" 19 | "strings" 20 | "testing" 21 | ) 22 | 23 | func assert_equals_string(one, two []string) bool { 24 | if len(one) != len(two) { 25 | return false 26 | } 27 | for i := 0; i < len(one); i++ { 28 | if one[i] != two[i] { 29 | return false 30 | } 31 | } 32 | return true 33 | } 34 | 35 | func TestSplitURLPath(t *testing.T) { 36 | 37 | var table = map[string][2][]string{ 38 | "/*name": {{"/", "*"}, {"name"}}, 39 | "/users/:name": {{"/users/", ":"}, {"name"}}, 40 | "/users/:name/put": {{"/users/", ":", "/put"}, {"name"}}, 41 | "/users/:name/put/:section": {{"/users/", ":", "/put/", ":"}, {"name", "section"}}, 42 | "/customers/:name/put/:section": {{"/customers/", ":", "/put/", ":"}, {"name", "section"}}, 43 | "/customers/groups/:name/put/:section": {{"/customers/groups/", ":", "/put/", ":"}, {"name", "section"}}, 44 | } 45 | 46 | for path, result := range table { 47 | parts, names := splitURLpath(path) 48 | if !assert_equals_string(parts, result[0]) { 49 | t.Errorf("Expected %v %v: %v %v", result[0], result[1], parts, names) 50 | } 51 | } 52 | } 53 | 54 | var testTable = [][]string{ 55 | {"/public/*fpath", "/public/index.html", "/public/favicon.png", "/public/images/bg.gif"}, 56 | {"/index", "/index"}, 57 | {"/users/:userId", "/users/666f24b7-cf7f-4176-bf07-c6d937e622c9"}, 58 | {"/users/:userId/companies/:companyId", "/users/666f24b7-cf7f-4176-bf07-c6d937e622c9/companies/666f24b7-cf7f-4176-bf07-c6d937e622c9"}, 59 | {"/us", "/us"}, 60 | {"/*fpath", "/", "/site_1/index.html", "/site_1/favicon.png", "/site_1/images/bg.gif"}, 61 | } 62 | 63 | func TestTreeLookupSimple(t *testing.T) { 64 | router := New() 65 | 66 | for _, v := range testTable { 67 | v := v 68 | router.AddRoute("GET", v[0], func(w http.ResponseWriter, r *http.Request, vp Parameter) { 69 | for i := 1; i < len(v); i++ { 70 | if r.URL.Path == v[i] { 71 | return 72 | } 73 | } 74 | t.Errorf("GOT %s EXPECTED %s\n", r.URL.Path, v) 75 | }) 76 | } 77 | 78 | t.Log(router.String()) 79 | 80 | for _, v := range testTable { 81 | for i := 1; i < len(v); i++ { 82 | t.Log("GET " + v[i]) 83 | fn, variables := router.FindRoute("GET", v[i]) 84 | if fn == nil { 85 | t.Error("Not Found", v[i], variables) 86 | continue 87 | } 88 | req, _ := http.NewRequest("GET", v[i], nil) 89 | fn(nil, req, variables) 90 | } 91 | } 92 | 93 | } 94 | 95 | func TestTreeIndicesBug(t *testing.T) { 96 | router := New() 97 | testTable := [][]string{ 98 | {"/", "/"}, 99 | {"/books", "/books"}, 100 | {"/source", "/source"}, 101 | } 102 | 103 | for _, v := range testTable { 104 | v := v 105 | router.AddRoute("GET", v[0], func(w http.ResponseWriter, r *http.Request, vp Parameter) { 106 | for i := 1; i < len(v); i++ { 107 | if r.URL.Path == v[i] { 108 | return 109 | } 110 | } 111 | t.Errorf("GOT %s EXPECTED %s\n", r.URL.Path, v) 112 | }) 113 | } 114 | 115 | for _, v := range testTable { 116 | for i := 1; i < len(v); i++ { 117 | t.Log("GET " + v[i]) 118 | fn, variables := router.FindRoute("GET", v[i]) 119 | if fn == nil { 120 | t.Error("Not Found", v[i], variables) 121 | continue 122 | } 123 | req, _ := http.NewRequest("GET", v[i], nil) 124 | fn(nil, req, variables) 125 | } 126 | } 127 | } 128 | 129 | var router = New() 130 | 131 | var benchRouter = New() 132 | var benchTest = [][]string{ 133 | {"/user/:name3/:userId/*path2", "name3", "userId", "path2"}, 134 | {"/user/:name2/list", "name2"}, 135 | {"/:name", "name"}, 136 | {"/user/:name/*path", "name", "path"}, 137 | {"/user/files/*path3", "path3"}, 138 | } 139 | 140 | func init() { 141 | 142 | for i := 0; i < len(benchTest); i++ { 143 | benchRouter.AddRoute("GET", benchTest[i][0], func(w http.ResponseWriter, r *http.Request, vp Parameter) { 144 | 145 | }) 146 | benchTest[i][0] = strings.NewReplacer(":", "", "*", "").Replace(benchTest[i][0]) 147 | } 148 | 149 | for _, v := range testTable { 150 | v := v 151 | router.AddRoute("GET", v[0], func(w http.ResponseWriter, r *http.Request, vp Parameter) { 152 | for i := 1; i < len(v); i++ { 153 | if r.URL.Path == v[i] { 154 | return 155 | } 156 | } 157 | }) 158 | } 159 | } 160 | 161 | func TestGetParam(t *testing.T) { 162 | for i := 0; i < len(benchTest); i++ { 163 | fn, vl := benchRouter.FindRoute("GET", benchTest[i][0]) 164 | if fn == nil { 165 | t.Errorf("%q was not found \n %s", benchTest[i][0], benchRouter) 166 | } 167 | for j := 1; j < len(benchTest[i]); j++ { 168 | param := vl.Get(benchTest[i][j]) 169 | if param != benchTest[i][j] { 170 | t.Errorf("%s Expected param %q get %q", benchTest[i][0], benchTest[i][j], param) 171 | } 172 | } 173 | } 174 | } 175 | 176 | func BenchmarkGetParam1(b *testing.B) { 177 | for i := 0; i < b.N; i++ { 178 | benchtest := benchTest[0] 179 | _, vl := benchRouter.FindRoute("GET", benchtest[0]) 180 | param := vl.Get(benchtest[1]) 181 | if param != benchtest[1] { 182 | b.Errorf("Expected param %q get %q", benchtest[1], param) 183 | } 184 | } 185 | } 186 | 187 | func BenchmarkGetParams(b *testing.B) { 188 | for i := 0; i < b.N; i++ { 189 | for i := 0; i < len(benchTest); i++ { 190 | fn, vl := benchRouter.FindRoute("GET", benchTest[i][0]) 191 | if fn == nil { 192 | b.Errorf("%q was not found", benchTest[i][0]) 193 | } 194 | for j := 1; j < len(benchTest[i]); j++ { 195 | param := vl.Get(benchTest[i][j]) 196 | if param != benchTest[i][j] { 197 | b.Errorf("Expected param %q get %q", benchTest[i][j], param) 198 | } 199 | } 200 | } 201 | } 202 | } 203 | 204 | func BenchmarkWildCard(b *testing.B) { 205 | for i := 0; i < b.N; i++ { 206 | fn, _ := router.FindRoute("GET", testTable[0][1]) 207 | if fn == nil { 208 | b.Error("Not Found", testTable[0][1]) 209 | continue 210 | } 211 | } 212 | } 213 | 214 | func BenchmarkPart(b *testing.B) { 215 | for i := 0; i < b.N; i++ { 216 | fn, _ := router.FindRoute("GET", testTable[3][1]) 217 | if fn == nil { 218 | b.Error("Not Found", testTable[3][1]) 219 | continue 220 | } 221 | } 222 | } 223 | 224 | func BenchmarkManyURLS(b *testing.B) { 225 | for i := 0; i < b.N; i++ { 226 | for _, v := range testTable { 227 | for i := 1; i < len(v); i++ { 228 | fn, _ := router.FindRoute("GET", v[i]) 229 | if fn == nil { 230 | b.Error("Not Found", v[i]) 231 | continue 232 | } 233 | } 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /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 2016 José Santos 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 | --------------------------------------------------------------------------------