├── .gitignore ├── .travis.yml ├── HttpRouterLicense ├── LICENSE ├── README.md ├── examples ├── auth.go ├── basic.go ├── examples └── hosts.go ├── path.go ├── path_test.go ├── router.go ├── router_test.go ├── tree.go └── tree_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | 3 | examples/basic 4 | examples/hosts 5 | examples/auth 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: go 3 | 4 | go: 5 | - 1.5 6 | - tip 7 | 8 | before_install: 9 | - go get -v github.com/axw/gocov/gocov 10 | - go get -v github.com/mattn/goveralls 11 | - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi 12 | - go get -v golang.org/x/tools/cmd/vet 13 | - go get -v github.com/golang/lint/golint 14 | 15 | install: 16 | - go get -d -t -v ./... 17 | - go install -v 18 | 19 | script: 20 | - go vet ./... 21 | - $HOME/gopath/bin/golint ./... 22 | - go test -v . 23 | - $HOME/gopath/bin/goveralls -service=travis-ci 24 | 25 | -------------------------------------------------------------------------------- /HttpRouterLicense: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Julien Schmidt. All rights reserved. 2 | 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * The names of the contributors may not be used to endorse or promote 12 | products derived from this software without specific prior written 13 | permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL JULIEN SCHMIDT BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, 招牌疯子 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of uq nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FastHttpRouter 2 | [![Build Status](https://travis-ci.org/buaazp/fasthttprouter.png?branch=master)](https://travis-ci.org/buaazp/fasthttprouter) 3 | [![Coverage Status](https://coveralls.io/repos/buaazp/fasthttprouter/badge.svg?branch=master&service=github)](https://coveralls.io/github/buaazp/fasthttprouter?branch=master) 4 | [![GoDoc](http://godoc.org/github.com/buaazp/fasthttprouter?status.png)](http://godoc.org/github.com/buaazp/fasthttprouter) 5 | 6 | FastHttpRouter is forked from [httprouter](https://github.com/julienschmidt/httprouter) which is a lightweight high performance HTTP request router 7 | (also called *multiplexer* or just *mux* for short) for [fasthttp](https://github.com/valyala/fasthttp). 8 | 9 | In contrast to the [RequestHandler](https://godoc.org/github.com/valyala/fasthttp#RequestHandler) functions of valyala's `fasthttp` package, this router supports variables in the routing pattern and matches against the request method. It also scales better. 10 | 11 | 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. 12 | 13 | ## Features 14 | 15 | **Only explicit matches:** With other routers, like [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux), 16 | a requested URL path could match multiple patterns. Therefore they have some 17 | awkward pattern priority rules, like *longest match* or *first registered, 18 | first matched*. By design of this router, a request can only match exactly one 19 | or no route. As a result, there are also no unintended matches, which makes it 20 | great for SEO and improves the user experience. 21 | 22 | **Stop caring about trailing slashes:** Choose the URL style you like, the 23 | router automatically redirects the client if a trailing slash is missing or if 24 | there is one extra. Of course it only does so, if the new path has a handler. 25 | If you don't like it, you can [turn off this behavior](http://godoc.org/github.com/buaazp/fasthttprouter#Router.RedirectTrailingSlash). 26 | 27 | **Path auto-correction:** Besides detecting the missing or additional trailing 28 | slash at no extra cost, the router can also fix wrong cases and remove 29 | superfluous path elements (like `../` or `//`). 30 | Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? 31 | FastHttpRouter can help him by making a case-insensitive look-up and redirecting him 32 | to the correct URL. 33 | 34 | **Parameters in your routing pattern:** Stop parsing the requested URL path, 35 | just give the path segment a name and the router delivers the dynamic value to 36 | you. Because of the design of the router, path parameters are very cheap. 37 | 38 | **Zero Garbage:** The matching and dispatching process generates zero bytes of 39 | garbage. In fact, the only heap allocations that are made, is by building the 40 | slice of the key-value pairs for path parameters. If the request path contains 41 | no parameters, not a single heap allocation is necessary. 42 | 43 | **Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). 44 | See below for technical details of the implementation. 45 | 46 | **No more server crashes:** You can set a [Panic handler](http://godoc.org/github.com/buaazp/fasthttprouter#Router.PanicHandler) to deal with panics 47 | occurring during handling a HTTP request. The router then recovers and lets the 48 | PanicHandler log what happened and deliver a nice error page. 49 | 50 | **Perfect for APIs:** The router design encourages to build sensible, hierarchical 51 | RESTful APIs. Moreover it has builtin native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) 52 | and `405 Method Not Allowed` replies. 53 | 54 | Of course you can also set **custom [NotFound](http://godoc.org/github.com/buaazp/fasthttprouter#Router.NotFound) and [MethodNotAllowed](http://godoc.org/github.com/buaazp/fasthttprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](http://godoc.org/github.com/buaazp/fasthttprouter#Router.ServeFiles). 55 | 56 | ## Usage 57 | 58 | This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/buaazp/fasthttprouter) for details. 59 | 60 | Let's start with a trivial example: 61 | 62 | ```go 63 | package main 64 | 65 | import ( 66 | "fmt" 67 | "log" 68 | 69 | "github.com/buaazp/fasthttprouter" 70 | "github.com/valyala/fasthttp" 71 | ) 72 | 73 | func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 74 | fmt.Fprint(ctx, "Welcome!\n") 75 | } 76 | 77 | func Hello(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 78 | fmt.Fprintf(ctx, "hello, %s!\n", ps.ByName("name")) 79 | } 80 | 81 | func main() { 82 | router := fasthttprouter.New() 83 | router.GET("/", Index) 84 | router.GET("/hello/:name", Hello) 85 | 86 | log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler)) 87 | } 88 | ``` 89 | 90 | ### Named parameters 91 | 92 | As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.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")`. 93 | 94 | Named parameters only match a single path segment: 95 | 96 | ``` 97 | Pattern: /user/:user 98 | 99 | /user/gordon match 100 | /user/you match 101 | /user/gordon/profile no match 102 | /user/ no match 103 | ``` 104 | 105 | **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. 106 | 107 | ### Catch-All parameters 108 | 109 | The second type are *catch-all* parameters and have the form `*name`. 110 | Like the name suggests, they match everything. 111 | Therefore they must always be at the **end** of the pattern: 112 | 113 | ``` 114 | Pattern: /src/*filepath 115 | 116 | /src/ match 117 | /src/somefile.go match 118 | /src/subdir/somefile.go match 119 | ``` 120 | 121 | ## How does it work? 122 | 123 | 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: 124 | 125 | ``` 126 | Priority Path Handle 127 | 9 \ *<1> 128 | 3 ├s nil 129 | 2 |├earch\ *<2> 130 | 1 |└upport\ *<3> 131 | 2 ├blog\ *<4> 132 | 1 | └:post nil 133 | 1 | └\ *<5> 134 | 2 ├about-us\ *<6> 135 | 1 | └team\ *<7> 136 | 1 └contact\ *<8> 137 | ``` 138 | 139 | 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][benchmark], this works very well and efficient. 140 | 141 | Since URL 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, for another thing is also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree. 142 | 143 | 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: 144 | 145 | 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. 146 | 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. 147 | 148 | ``` 149 | ├------------ 150 | ├--------- 151 | ├----- 152 | ├---- 153 | ├-- 154 | ├-- 155 | └- 156 | ``` 157 | 158 | ## Why doesn't this work with `http.Handler`? 159 | 160 | Becasue fasthttp doesn't provide http.Handler. See this [description](https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp). 161 | 162 | Fasthttp works with [RequestHandler](https://godoc.org/github.com/valyala/fasthttp#RequestHandler) functions instead of objects implementing Handler interface. So a FastHttpRouter provides a [Handler](https://godoc.org/github.com/buaazp/fasthttprouter#Router.Handler) interface to implement the fasthttp.ListenAndServe interface. 163 | 164 | Just try it out for yourself, the usage of FastHttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up. 165 | 166 | Just try it out for yourself, the usage of FastHttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up. 167 | 168 | ## Where can I find Middleware *X*? 169 | 170 | This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`][http.Handler], you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy! 171 | 172 | Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter). 173 | 174 | ### Multi-domain / Sub-domains 175 | 176 | Here is a quick example: Does your server serve multiple domains / hosts? 177 | You want to use sub-domains? 178 | Define a router per host! 179 | 180 | ```go 181 | // We need an object that implements the fasthttp.RequestHandler interface. 182 | // We just use a map here, in which we map host names (with port) to fasthttp.RequestHandlers 183 | type HostSwitch map[string]fasthttp.RequestHandler 184 | 185 | // Implement a CheckHost method on our new type 186 | func (hs HostSwitch) CheckHost(ctx *fasthttp.RequestCtx) { 187 | // Check if a http.Handler is registered for the given host. 188 | // If yes, use it to handle the request. 189 | if handler := hs[string(ctx.Host())]; handler != nil { 190 | handler(ctx) 191 | } else { 192 | // Handle host names for wich no handler is registered 193 | ctx.Error("Forbidden", 403) // Or Redirect? 194 | } 195 | } 196 | 197 | func main() { 198 | // Initialize a router as usual 199 | router := fasthttprouter.New() 200 | router.GET("/", Index) 201 | router.GET("/hello/:name", Hello) 202 | 203 | // Make a new HostSwitch and insert the router (our http handler) 204 | // for example.com and port 12345 205 | hs := make(HostSwitch) 206 | hs["example.com:12345"] = router.Handler 207 | 208 | // Use the HostSwitch to listen and serve on port 12345 209 | log.Fatal(fasthttp.ListenAndServe(":12345", hs.CheckHost)) 210 | } 211 | ``` 212 | 213 | ### Basic Authentication 214 | 215 | Another quick example: Basic Authentication (RFC 2617) for handles: 216 | 217 | ```go 218 | package main 219 | 220 | import ( 221 | "bytes" 222 | "encoding/base64" 223 | "fmt" 224 | "log" 225 | 226 | "github.com/buaazp/fasthttprouter" 227 | "github.com/valyala/fasthttp" 228 | ) 229 | 230 | var basicAuthPrefix = []byte("Basic ") 231 | 232 | func BasicAuth(h fasthttprouter.Handle, user, pass []byte) fasthttprouter.Handle { 233 | return fasthttprouter.Handle(func(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 234 | // Get the Basic Authentication credentials 235 | auth := ctx.Request.Header.Peek("Authorization") 236 | if bytes.HasPrefix(auth, basicAuthPrefix) { 237 | // Check credentials 238 | payload, err := base64.StdEncoding.DecodeString(string(auth[len(basicAuthPrefix):])) 239 | if err == nil { 240 | pair := bytes.SplitN(payload, []byte(":"), 2) 241 | if len(pair) == 2 && 242 | bytes.Equal(pair[0], user) && 243 | bytes.Equal(pair[1], pass) { 244 | // Delegate request to the given handle 245 | h(ctx, ps) 246 | return 247 | } 248 | } 249 | } 250 | 251 | // Request Basic Authentication otherwise 252 | ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted") 253 | ctx.Error(fasthttp.StatusMessage(fasthttp.StatusUnauthorized), fasthttp.StatusUnauthorized) 254 | }) 255 | } 256 | 257 | func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 258 | fmt.Fprint(ctx, "Not protected!\n") 259 | } 260 | 261 | func Protected(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 262 | fmt.Fprint(ctx, "Protected!\n") 263 | } 264 | 265 | func main() { 266 | user := []byte("gordon") 267 | pass := []byte("secret!") 268 | 269 | router := fasthttprouter.New() 270 | router.GET("/", Index) 271 | router.GET("/protected/", BasicAuth(Protected, user, pass)) 272 | 273 | log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler)) 274 | } 275 | ``` 276 | 277 | ## Chaining with the NotFound handler 278 | 279 | **NOTE: It might be required to set [Router.HandleMethodNotAllowed](http://godoc.org/github.com/buaazp/fasthttprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.** 280 | 281 | You can use another [http.Handler](http://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [Router.NotFound](http://godoc.org/github.com/buaazp/fasthttprouter#Router.NotFound) handler. This allows chaining. 282 | 283 | ### Static files 284 | The `NotFound` handler can for example be used to serve static files from the root path `/` (like an index.html file along with other assets): 285 | 286 | ```go 287 | // Serve static files from the ./public directory 288 | router.NotFound = fasthttp.FSHandler("./public", 0) 289 | ``` 290 | 291 | But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`. 292 | 293 | ## Web Frameworks based on FastHttpRouter 294 | 295 | If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package: 296 | 297 | - Waiting for you to do this... 298 | -------------------------------------------------------------------------------- /examples/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "fmt" 7 | "log" 8 | 9 | "github.com/buaazp/fasthttprouter" 10 | "github.com/valyala/fasthttp" 11 | ) 12 | 13 | var basicAuthPrefix = []byte("Basic ") 14 | 15 | // BasicAuth is the basic auth handler 16 | func BasicAuth(h fasthttprouter.Handle, user, pass []byte) fasthttprouter.Handle { 17 | return fasthttprouter.Handle(func(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 18 | // Get the Basic Authentication credentials 19 | auth := ctx.Request.Header.Peek("Authorization") 20 | if bytes.HasPrefix(auth, basicAuthPrefix) { 21 | // Check credentials 22 | payload, err := base64.StdEncoding.DecodeString(string(auth[len(basicAuthPrefix):])) 23 | if err == nil { 24 | pair := bytes.SplitN(payload, []byte(":"), 2) 25 | if len(pair) == 2 && 26 | bytes.Equal(pair[0], user) && 27 | bytes.Equal(pair[1], pass) { 28 | // Delegate request to the given handle 29 | h(ctx, ps) 30 | return 31 | } 32 | } 33 | } 34 | 35 | // Request Basic Authentication otherwise 36 | ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted") 37 | ctx.Error(fasthttp.StatusMessage(fasthttp.StatusUnauthorized), fasthttp.StatusUnauthorized) 38 | }) 39 | } 40 | 41 | // Index is the index handler 42 | func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 43 | fmt.Fprint(ctx, "Not protected!\n") 44 | } 45 | 46 | // Protected is the Protected handler 47 | func Protected(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 48 | fmt.Fprint(ctx, "Protected!\n") 49 | } 50 | 51 | func main() { 52 | user := []byte("gordon") 53 | pass := []byte("secret!") 54 | 55 | router := fasthttprouter.New() 56 | router.GET("/", Index) 57 | router.GET("/protected/", BasicAuth(Protected, user, pass)) 58 | 59 | log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler)) 60 | } 61 | -------------------------------------------------------------------------------- /examples/basic.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/buaazp/fasthttprouter" 8 | "github.com/valyala/fasthttp" 9 | ) 10 | 11 | // Index is the index handler 12 | func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 13 | fmt.Fprint(ctx, "Welcome!\n") 14 | } 15 | 16 | // Hello is the Hello handler 17 | func Hello(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 18 | fmt.Fprintf(ctx, "hello, %s!\n", ps.ByName("name")) 19 | } 20 | 21 | func main() { 22 | router := fasthttprouter.New() 23 | router.GET("/", Index) 24 | router.GET("/hello/:name", Hello) 25 | 26 | log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler)) 27 | } 28 | -------------------------------------------------------------------------------- /examples/examples: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/valyala/fasthttprouter/24073dd8f323cb52fe24f2f51bda5e6b1c2a0f18/examples/examples -------------------------------------------------------------------------------- /examples/hosts.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/buaazp/fasthttprouter" 8 | "github.com/valyala/fasthttp" 9 | ) 10 | 11 | // Index is the index handler 12 | func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 13 | fmt.Fprint(ctx, "Welcome!\n") 14 | } 15 | 16 | // Hello is the Hello handler 17 | func Hello(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 18 | fmt.Fprintf(ctx, "hello, %s!\n", ps.ByName("name")) 19 | } 20 | 21 | // HostSwitch is the host-handler map 22 | // We need an object that implements the fasthttp.RequestHandler interface. 23 | // We just use a map here, in which we map host names (with port) to fasthttp.RequestHandlers 24 | type HostSwitch map[string]fasthttp.RequestHandler 25 | 26 | // CheckHost Implement a CheckHost method on our new type 27 | func (hs HostSwitch) CheckHost(ctx *fasthttp.RequestCtx) { 28 | // Check if a http.Handler is registered for the given host. 29 | // If yes, use it to handle the request. 30 | if handler := hs[string(ctx.Host())]; handler != nil { 31 | handler(ctx) 32 | } else { 33 | // Handle host names for wich no handler is registered 34 | ctx.Error("Forbidden", 403) // Or Redirect? 35 | } 36 | } 37 | 38 | func main() { 39 | // Initialize a router as usual 40 | router := fasthttprouter.New() 41 | router.GET("/", Index) 42 | router.GET("/hello/:name", Hello) 43 | 44 | // Make a new HostSwitch and insert the router (our http handler) 45 | // for example.com and port 12345 46 | hs := make(HostSwitch) 47 | hs["example.com:12345"] = router.Handler 48 | 49 | // Use the HostSwitch to listen and serve on port 12345 50 | log.Fatal(fasthttp.ListenAndServe(":12345", hs.CheckHost)) 51 | } 52 | -------------------------------------------------------------------------------- /path.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Based on the path package, Copyright 2009 The Go Authors. 3 | // Use of this source code is governed by a BSD-style license that can be found 4 | // in the LICENSE file. 5 | 6 | package fasthttprouter 7 | 8 | // CleanPath is the URL version of path.Clean, it returns a canonical URL path 9 | // for p, eliminating . and .. elements. 10 | // 11 | // The following rules are applied iteratively until no further processing can 12 | // be done: 13 | // 1. Replace multiple slashes with a single slash. 14 | // 2. Eliminate each . path name element (the current directory). 15 | // 3. Eliminate each inner .. path name element (the parent directory) 16 | // along with the non-.. element that precedes it. 17 | // 4. Eliminate .. elements that begin a rooted path: 18 | // that is, replace "/.." by "/" at the beginning of a path. 19 | // 20 | // If the result of this process is an empty string, "/" is returned 21 | func CleanPath(p string) string { 22 | // Turn empty string into "/" 23 | if p == "" { 24 | return "/" 25 | } 26 | 27 | n := len(p) 28 | var buf []byte 29 | 30 | // Invariants: 31 | // reading from path; r is index of next byte to process. 32 | // writing to buf; w is index of next byte to write. 33 | 34 | // path must start with '/' 35 | r := 1 36 | w := 1 37 | 38 | if p[0] != '/' { 39 | r = 0 40 | buf = make([]byte, n+1) 41 | buf[0] = '/' 42 | } 43 | 44 | trailing := n > 2 && p[n-1] == '/' 45 | 46 | // A bit more clunky without a 'lazybuf' like the path package, but the loop 47 | // gets completely inlined (bufApp). So in contrast to the path package this 48 | // loop has no expensive function calls (except 1x make) 49 | 50 | for r < n { 51 | switch { 52 | case p[r] == '/': 53 | // empty path element, trailing slash is added after the end 54 | r++ 55 | 56 | case p[r] == '.' && r+1 == n: 57 | trailing = true 58 | r++ 59 | 60 | case p[r] == '.' && p[r+1] == '/': 61 | // . element 62 | r++ 63 | 64 | case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): 65 | // .. element: remove to last / 66 | r += 2 67 | 68 | if w > 1 { 69 | // can backtrack 70 | w-- 71 | 72 | if buf == nil { 73 | for w > 1 && p[w] != '/' { 74 | w-- 75 | } 76 | } else { 77 | for w > 1 && buf[w] != '/' { 78 | w-- 79 | } 80 | } 81 | } 82 | 83 | default: 84 | // real path element. 85 | // add slash if needed 86 | if w > 1 { 87 | bufApp(&buf, p, w, '/') 88 | w++ 89 | } 90 | 91 | // copy element 92 | for r < n && p[r] != '/' { 93 | bufApp(&buf, p, w, p[r]) 94 | w++ 95 | r++ 96 | } 97 | } 98 | } 99 | 100 | // re-append trailing slash 101 | if trailing && w > 1 { 102 | bufApp(&buf, p, w, '/') 103 | w++ 104 | } 105 | 106 | if buf == nil { 107 | return p[:w] 108 | } 109 | return string(buf[:w]) 110 | } 111 | 112 | // internal helper to lazily create a buffer if necessary 113 | func bufApp(buf *[]byte, s string, w int, c byte) { 114 | if *buf == nil { 115 | if s[w] == c { 116 | return 117 | } 118 | 119 | *buf = make([]byte, len(s)) 120 | copy(*buf, s[:w]) 121 | } 122 | (*buf)[w] = c 123 | } 124 | -------------------------------------------------------------------------------- /path_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Based on the path package, Copyright 2009 The Go Authors. 3 | // Use of this source code is governed by a BSD-style license that can be found 4 | // in the LICENSE file. 5 | 6 | package fasthttprouter 7 | 8 | import ( 9 | "runtime" 10 | "testing" 11 | ) 12 | 13 | var cleanTests = []struct { 14 | path, result string 15 | }{ 16 | // Already clean 17 | {"/", "/"}, 18 | {"/abc", "/abc"}, 19 | {"/a/b/c", "/a/b/c"}, 20 | {"/abc/", "/abc/"}, 21 | {"/a/b/c/", "/a/b/c/"}, 22 | 23 | // missing root 24 | {"", "/"}, 25 | {"abc", "/abc"}, 26 | {"abc/def", "/abc/def"}, 27 | {"a/b/c", "/a/b/c"}, 28 | 29 | // Remove doubled slash 30 | {"//", "/"}, 31 | {"/abc//", "/abc/"}, 32 | {"/abc/def//", "/abc/def/"}, 33 | {"/a/b/c//", "/a/b/c/"}, 34 | {"/abc//def//ghi", "/abc/def/ghi"}, 35 | {"//abc", "/abc"}, 36 | {"///abc", "/abc"}, 37 | {"//abc//", "/abc/"}, 38 | 39 | // Remove . elements 40 | {".", "/"}, 41 | {"./", "/"}, 42 | {"/abc/./def", "/abc/def"}, 43 | {"/./abc/def", "/abc/def"}, 44 | {"/abc/.", "/abc/"}, 45 | 46 | // Remove .. elements 47 | {"..", "/"}, 48 | {"../", "/"}, 49 | {"../../", "/"}, 50 | {"../..", "/"}, 51 | {"../../abc", "/abc"}, 52 | {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, 53 | {"/abc/def/../ghi/../jkl", "/abc/jkl"}, 54 | {"/abc/def/..", "/abc"}, 55 | {"/abc/def/../..", "/"}, 56 | {"/abc/def/../../..", "/"}, 57 | {"/abc/def/../../..", "/"}, 58 | {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, 59 | 60 | // Combinations 61 | {"abc/./../def", "/def"}, 62 | {"abc//./../def", "/def"}, 63 | {"abc/../../././../def", "/def"}, 64 | } 65 | 66 | func TestPathClean(t *testing.T) { 67 | for _, test := range cleanTests { 68 | if s := CleanPath(test.path); s != test.result { 69 | t.Errorf("CleanPath(%q) = %q, want %q", test.path, s, test.result) 70 | } 71 | if s := CleanPath(test.result); s != test.result { 72 | t.Errorf("CleanPath(%q) = %q, want %q", test.result, s, test.result) 73 | } 74 | } 75 | } 76 | 77 | func TestPathCleanMallocs(t *testing.T) { 78 | if testing.Short() { 79 | t.Skip("skipping malloc count in short mode") 80 | } 81 | if runtime.GOMAXPROCS(0) > 1 { 82 | t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1") 83 | return 84 | } 85 | 86 | for _, test := range cleanTests { 87 | allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) }) 88 | if allocs > 0 { 89 | t.Errorf("CleanPath(%q): %v allocs, want zero", test.result, allocs) 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /router.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be found 3 | // in the LICENSE file. 4 | 5 | // Package fasthttprouter is a trie based high performance HTTP request router. 6 | // 7 | // A trivial example is: 8 | // 9 | // package main 10 | 11 | // import ( 12 | // "fmt" 13 | // "log" 14 | // 15 | // "github.com/buaazp/fasthttprouter" 16 | // "github.com/valyala/fasthttp" 17 | // ) 18 | 19 | // func Index(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { 20 | // fmt.Fprint(ctx, "Welcome!\n") 21 | // } 22 | 23 | // func Hello(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { 24 | // fmt.Fprintf(ctx, "hello, %s!\n", ps.ByName("name")) 25 | // } 26 | 27 | // func main() { 28 | // router := fasthttprouter.New() 29 | // router.GET("/", Index) 30 | // router.GET("/hello/:name", Hello) 31 | 32 | // log.Fatal(fasthttp.ListenAndServe(":8080", router.Handler)) 33 | // } 34 | // 35 | // The router matches incoming requests by the request method and the path. 36 | // If a handle is registered for this path and method, the router delegates the 37 | // request to that function. 38 | // For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to 39 | // register handles, for all other methods router.Handle can be used. 40 | // 41 | // The registered path, against which the router matches incoming requests, can 42 | // contain two types of parameters: 43 | // Syntax Type 44 | // :name named parameter 45 | // *name catch-all parameter 46 | // 47 | // Named parameters are dynamic path segments. They match anything until the 48 | // next '/' or the path end: 49 | // Path: /blog/:category/:post 50 | // 51 | // Requests: 52 | // /blog/go/request-routers match: category="go", post="request-routers" 53 | // /blog/go/request-routers/ no match, but the router would redirect 54 | // /blog/go/ no match 55 | // /blog/go/request-routers/comments no match 56 | // 57 | // Catch-all parameters match anything until the path end, including the 58 | // directory index (the '/' before the catch-all). Since they match anything 59 | // until the end, catch-all parameters must always be the final path element. 60 | // Path: /files/*filepath 61 | // 62 | // Requests: 63 | // /files/ match: filepath="/" 64 | // /files/LICENSE match: filepath="/LICENSE" 65 | // /files/templates/article.html match: filepath="/templates/article.html" 66 | // /files no match, but the router would redirect 67 | // 68 | // The value of parameters is saved as a slice of the Param struct, consisting 69 | // each of a key and a value. The slice is passed to the Handle func as a third 70 | // parameter. 71 | // There are two ways to retrieve the value of a parameter: 72 | // // by the name of the parameter 73 | // user := ps.ByName("user") // defined by :user or *user 74 | // 75 | // // by the index of the parameter. This way you can also get the name (key) 76 | // thirdKey := ps[2].Key // the name of the 3rd parameter 77 | // thirdValue := ps[2].Value // the value of the 3rd parameter 78 | 79 | package fasthttprouter 80 | 81 | import ( 82 | "strings" 83 | 84 | "github.com/valyala/fasthttp" 85 | ) 86 | 87 | var ( 88 | defaultContentType = []byte("text/plain; charset=utf-8") 89 | ) 90 | 91 | // Handle is a function that can be registered to a route to handle HTTP 92 | // requests. Like http.HandlerFunc, but has a third parameter for the values of 93 | // wildcards (variables). 94 | type Handle func(*fasthttp.RequestCtx, Params) 95 | 96 | // Param is a single URL parameter, consisting of a key and a value. 97 | type Param struct { 98 | Key string 99 | Value string 100 | } 101 | 102 | // Params is a Param-slice, as returned by the router. 103 | // The slice is ordered, the first URL parameter is also the first slice value. 104 | // It is therefore safe to read values by the index. 105 | type Params []Param 106 | 107 | // ByName returns the value of the first Param which key matches the given name. 108 | // If no matching Param is found, an empty string is returned. 109 | func (ps Params) ByName(name string) string { 110 | for i := range ps { 111 | if ps[i].Key == name { 112 | return ps[i].Value 113 | } 114 | } 115 | return "" 116 | } 117 | 118 | // Router is a http.Handler which can be used to dispatch requests to different 119 | // handler functions via configurable routes 120 | type Router struct { 121 | trees map[string]*node 122 | 123 | // Enables automatic redirection if the current route can't be matched but a 124 | // handler for the path with (without) the trailing slash exists. 125 | // For example if /foo/ is requested but a route only exists for /foo, the 126 | // client is redirected to /foo with http status code 301 for GET requests 127 | // and 307 for all other request methods. 128 | RedirectTrailingSlash bool 129 | 130 | // If enabled, the router tries to fix the current request path, if no 131 | // handle is registered for it. 132 | // First superfluous path elements like ../ or // are removed. 133 | // Afterwards the router does a case-insensitive lookup of the cleaned path. 134 | // If a handle can be found for this route, the router makes a redirection 135 | // to the corrected path with status code 301 for GET requests and 307 for 136 | // all other request methods. 137 | // For example /FOO and /..//Foo could be redirected to /foo. 138 | // RedirectTrailingSlash is independent of this option. 139 | RedirectFixedPath bool 140 | 141 | // If enabled, the router checks if another method is allowed for the 142 | // current route, if the current request can not be routed. 143 | // If this is the case, the request is answered with 'Method Not Allowed' 144 | // and HTTP status code 405. 145 | // If no other Method is allowed, the request is delegated to the NotFound 146 | // handler. 147 | HandleMethodNotAllowed bool 148 | 149 | // If enabled, the router automatically replies to OPTIONS requests. 150 | // Custom OPTIONS handlers take priority over automatic replies. 151 | HandleOPTIONS bool 152 | 153 | // Configurable http.Handler which is called when no matching route is 154 | // found. If it is not set, http.NotFound is used. 155 | NotFound fasthttp.RequestHandler 156 | 157 | // Configurable http.Handler which is called when a request 158 | // cannot be routed and HandleMethodNotAllowed is true. 159 | // If it is not set, http.Error with http.StatusMethodNotAllowed is used. 160 | // The "Allow" header with allowed request methods is set before the handler 161 | // is called. 162 | MethodNotAllowed fasthttp.RequestHandler 163 | 164 | // Function to handle panics recovered from http handlers. 165 | // It should be used to generate a error page and return the http error code 166 | // 500 (Internal Server Error). 167 | // The handler can be used to keep your server from crashing because of 168 | // unrecovered panics. 169 | PanicHandler func(*fasthttp.RequestCtx, interface{}) 170 | } 171 | 172 | // New returns a new initialized Router. 173 | // Path auto-correction, including trailing slashes, is enabled by default. 174 | func New() *Router { 175 | return &Router{ 176 | RedirectTrailingSlash: true, 177 | RedirectFixedPath: true, 178 | HandleMethodNotAllowed: true, 179 | HandleOPTIONS: true, 180 | } 181 | } 182 | 183 | // GET is a shortcut for router.Handle("GET", path, handle) 184 | func (r *Router) GET(path string, handle Handle) { 185 | r.Handle("GET", path, handle) 186 | } 187 | 188 | // HEAD is a shortcut for router.Handle("HEAD", path, handle) 189 | func (r *Router) HEAD(path string, handle Handle) { 190 | r.Handle("HEAD", path, handle) 191 | } 192 | 193 | // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) 194 | func (r *Router) OPTIONS(path string, handle Handle) { 195 | r.Handle("OPTIONS", path, handle) 196 | } 197 | 198 | // POST is a shortcut for router.Handle("POST", path, handle) 199 | func (r *Router) POST(path string, handle Handle) { 200 | r.Handle("POST", path, handle) 201 | } 202 | 203 | // PUT is a shortcut for router.Handle("PUT", path, handle) 204 | func (r *Router) PUT(path string, handle Handle) { 205 | r.Handle("PUT", path, handle) 206 | } 207 | 208 | // PATCH is a shortcut for router.Handle("PATCH", path, handle) 209 | func (r *Router) PATCH(path string, handle Handle) { 210 | r.Handle("PATCH", path, handle) 211 | } 212 | 213 | // DELETE is a shortcut for router.Handle("DELETE", path, handle) 214 | func (r *Router) DELETE(path string, handle Handle) { 215 | r.Handle("DELETE", path, handle) 216 | } 217 | 218 | // Handle registers a new request handle with the given path and method. 219 | // 220 | // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut 221 | // functions can be used. 222 | // 223 | // This function is intended for bulk loading and to allow the usage of less 224 | // frequently used, non-standardized or custom methods (e.g. for internal 225 | // communication with a proxy). 226 | func (r *Router) Handle(method, path string, handle Handle) { 227 | if path[0] != '/' { 228 | panic("path must begin with '/' in path '" + path + "'") 229 | } 230 | 231 | if r.trees == nil { 232 | r.trees = make(map[string]*node) 233 | } 234 | 235 | root := r.trees[method] 236 | if root == nil { 237 | root = new(node) 238 | r.trees[method] = root 239 | } 240 | 241 | root.addRoute(path, handle) 242 | } 243 | 244 | // ServeFiles serves files from the given file system root. 245 | // The path must end with "/*filepath", files are then served from the local 246 | // path /defined/root/dir/*filepath. 247 | // For example if root is "/etc" and *filepath is "passwd", the local file 248 | // "/etc/passwd" would be served. 249 | // Internally a http.FileServer is used, therefore http.NotFound is used instead 250 | // of the Router's NotFound handler. 251 | // router.ServeFiles("/src/*filepath", "/var/www") 252 | func (r *Router) ServeFiles(path string, rootPath string) { 253 | if len(path) < 10 || path[len(path)-10:] != "/*filepath" { 254 | panic("path must end with /*filepath in path '" + path + "'") 255 | } 256 | prefix := path[:len(path)-10] 257 | 258 | fileHandler := fasthttp.FSHandler(rootPath, strings.Count(prefix, "/")) 259 | 260 | r.GET(path, func(ctx *fasthttp.RequestCtx, _ Params) { 261 | fileHandler(ctx) 262 | }) 263 | } 264 | 265 | func (r *Router) recv(ctx *fasthttp.RequestCtx) { 266 | if rcv := recover(); rcv != nil { 267 | r.PanicHandler(ctx, rcv) 268 | } 269 | } 270 | 271 | // Lookup allows the manual lookup of a method + path combo. 272 | // This is e.g. useful to build a framework around this router. 273 | // If the path was found, it returns the handle function and the path parameter 274 | // values. Otherwise the third return value indicates whether a redirection to 275 | // the same path with an extra / without the trailing slash should be performed. 276 | func (r *Router) Lookup(method, path string) (Handle, Params, bool) { 277 | if root := r.trees[method]; root != nil { 278 | return root.getValue(path) 279 | } 280 | return nil, nil, false 281 | } 282 | 283 | func (r *Router) allowed(path, reqMethod string) (allow string) { 284 | if path == "*" || path == "/*" { // server-wide 285 | for method := range r.trees { 286 | if method == "OPTIONS" { 287 | continue 288 | } 289 | 290 | // add request method to list of allowed methods 291 | if len(allow) == 0 { 292 | allow = method 293 | } else { 294 | allow += ", " + method 295 | } 296 | } 297 | } else { // specific path 298 | for method := range r.trees { 299 | // Skip the requested method - we already tried this one 300 | if method == reqMethod || method == "OPTIONS" { 301 | continue 302 | } 303 | 304 | handle, _, _ := r.trees[method].getValue(path) 305 | if handle != nil { 306 | // add request method to list of allowed methods 307 | if len(allow) == 0 { 308 | allow = method 309 | } else { 310 | allow += ", " + method 311 | } 312 | } 313 | } 314 | } 315 | if len(allow) > 0 { 316 | allow += ", OPTIONS" 317 | } 318 | return 319 | } 320 | 321 | // Handler makes the router implement the fasthttp.ListenAndServe interface. 322 | func (r *Router) Handler(ctx *fasthttp.RequestCtx) { 323 | if r.PanicHandler != nil { 324 | defer r.recv(ctx) 325 | } 326 | 327 | path := string(ctx.Path()) 328 | method := string(ctx.Method()) 329 | if root := r.trees[method]; root != nil { 330 | if f, ps, tsr := root.getValue(path); f != nil { 331 | f(ctx, ps) 332 | return 333 | } else if method != "CONNECT" && path != "/" { 334 | code := 301 // Permanent redirect, request with GET method 335 | if method != "GET" { 336 | // Temporary redirect, request with same method 337 | // As of Go 1.3, Go does not support status code 308. 338 | code = 307 339 | } 340 | 341 | if tsr && r.RedirectTrailingSlash { 342 | var uri string 343 | if len(path) > 1 && path[len(path)-1] == '/' { 344 | uri = path[:len(path)-1] 345 | } else { 346 | uri = path + "/" 347 | } 348 | ctx.Redirect(uri, code) 349 | return 350 | } 351 | 352 | // Try to fix the request path 353 | if r.RedirectFixedPath { 354 | fixedPath, found := root.findCaseInsensitivePath( 355 | CleanPath(path), 356 | r.RedirectTrailingSlash, 357 | ) 358 | if found { 359 | uri := string(fixedPath) 360 | ctx.Redirect(uri, code) 361 | return 362 | } 363 | } 364 | } 365 | } 366 | 367 | if method == "OPTIONS" { 368 | // Handle OPTIONS requests 369 | if r.HandleOPTIONS { 370 | if allow := r.allowed(path, method); len(allow) > 0 { 371 | ctx.Response.Header.Set("Allow", allow) 372 | return 373 | } 374 | } 375 | } else { 376 | // Handle 405 377 | if r.HandleMethodNotAllowed { 378 | if allow := r.allowed(path, method); len(allow) > 0 { 379 | ctx.Response.Header.Set("Allow", allow) 380 | if r.MethodNotAllowed != nil { 381 | r.MethodNotAllowed(ctx) 382 | } else { 383 | ctx.SetStatusCode(fasthttp.StatusMethodNotAllowed) 384 | ctx.SetContentTypeBytes(defaultContentType) 385 | ctx.SetBodyString(fasthttp.StatusMessage(fasthttp.StatusMethodNotAllowed)) 386 | } 387 | return 388 | } 389 | } 390 | } 391 | 392 | // Handle 404 393 | if r.NotFound != nil { 394 | r.NotFound(ctx) 395 | } else { 396 | ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound), 397 | fasthttp.StatusNotFound) 398 | } 399 | } 400 | -------------------------------------------------------------------------------- /router_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be found 3 | // in the LICENSE file. 4 | 5 | package fasthttprouter 6 | 7 | import ( 8 | "bufio" 9 | "bytes" 10 | "errors" 11 | "fmt" 12 | "io/ioutil" 13 | "net" 14 | "net/http" 15 | "os" 16 | "reflect" 17 | "testing" 18 | "time" 19 | 20 | "github.com/valyala/fasthttp" 21 | ) 22 | 23 | func TestParams(t *testing.T) { 24 | ps := Params{ 25 | Param{"param1", "value1"}, 26 | Param{"param2", "value2"}, 27 | Param{"param3", "value3"}, 28 | } 29 | for i := range ps { 30 | if val := ps.ByName(ps[i].Key); val != ps[i].Value { 31 | t.Errorf("Wrong value for %s: Got %s; Want %s", ps[i].Key, val, ps[i].Value) 32 | } 33 | } 34 | if val := ps.ByName("noKey"); val != "" { 35 | t.Errorf("Expected empty string for not found key; got: %s", val) 36 | } 37 | } 38 | 39 | func TestRouter(t *testing.T) { 40 | router := New() 41 | 42 | routed := false 43 | router.Handle("GET", "/user/:name", func(ctx *fasthttp.RequestCtx, ps Params) { 44 | routed = true 45 | want := Params{Param{"name", "gopher"}} 46 | if !reflect.DeepEqual(ps, want) { 47 | t.Fatalf("wrong wildcard values: want %v, got %v", want, ps) 48 | } 49 | ctx.Success("foo/bar", []byte("success")) 50 | }) 51 | 52 | s := &fasthttp.Server{ 53 | Handler: router.Handler, 54 | } 55 | 56 | rw := &readWriter{} 57 | rw.r.WriteString("GET /user/gopher?baz HTTP/1.1\r\n\r\n") 58 | 59 | ch := make(chan error) 60 | go func() { 61 | ch <- s.ServeConn(rw) 62 | }() 63 | 64 | select { 65 | case err := <-ch: 66 | if err != nil { 67 | t.Fatalf("return error %s", err) 68 | } 69 | case <-time.After(100 * time.Millisecond): 70 | t.Fatalf("timeout") 71 | } 72 | 73 | if !routed { 74 | t.Fatal("routing failed") 75 | } 76 | } 77 | 78 | type handlerStruct struct { 79 | handeled *bool 80 | } 81 | 82 | func (h handlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) { 83 | *h.handeled = true 84 | } 85 | 86 | func TestRouterAPI(t *testing.T) { 87 | var get, head, options, post, put, patch, deleted bool 88 | 89 | router := New() 90 | router.GET("/GET", func(ctx *fasthttp.RequestCtx, _ Params) { 91 | get = true 92 | }) 93 | router.HEAD("/GET", func(ctx *fasthttp.RequestCtx, _ Params) { 94 | head = true 95 | }) 96 | router.OPTIONS("/GET", func(ctx *fasthttp.RequestCtx, _ Params) { 97 | options = true 98 | }) 99 | router.POST("/POST", func(ctx *fasthttp.RequestCtx, _ Params) { 100 | post = true 101 | }) 102 | router.PUT("/PUT", func(ctx *fasthttp.RequestCtx, _ Params) { 103 | put = true 104 | }) 105 | router.PATCH("/PATCH", func(ctx *fasthttp.RequestCtx, _ Params) { 106 | patch = true 107 | }) 108 | router.DELETE("/DELETE", func(ctx *fasthttp.RequestCtx, _ Params) { 109 | deleted = true 110 | }) 111 | 112 | s := &fasthttp.Server{ 113 | Handler: router.Handler, 114 | } 115 | 116 | rw := &readWriter{} 117 | ch := make(chan error) 118 | 119 | rw.r.WriteString("GET /GET HTTP/1.1\r\n\r\n") 120 | go func() { 121 | ch <- s.ServeConn(rw) 122 | }() 123 | select { 124 | case err := <-ch: 125 | if err != nil { 126 | t.Fatalf("return error %s", err) 127 | } 128 | case <-time.After(100 * time.Millisecond): 129 | t.Fatalf("timeout") 130 | } 131 | if !get { 132 | t.Error("routing GET failed") 133 | } 134 | 135 | rw.r.WriteString("HEAD /GET HTTP/1.1\r\n\r\n") 136 | go func() { 137 | ch <- s.ServeConn(rw) 138 | }() 139 | select { 140 | case err := <-ch: 141 | if err != nil { 142 | t.Fatalf("return error %s", err) 143 | } 144 | case <-time.After(100 * time.Millisecond): 145 | t.Fatalf("timeout") 146 | } 147 | if !head { 148 | t.Error("routing HEAD failed") 149 | } 150 | 151 | rw.r.WriteString("OPTIONS /GET HTTP/1.1\r\n\r\n") 152 | go func() { 153 | ch <- s.ServeConn(rw) 154 | }() 155 | select { 156 | case err := <-ch: 157 | if err != nil { 158 | t.Fatalf("return error %s", err) 159 | } 160 | case <-time.After(100 * time.Millisecond): 161 | t.Fatalf("timeout") 162 | } 163 | if !options { 164 | t.Error("routing OPTIONS failed") 165 | } 166 | 167 | rw.r.WriteString("POST /POST HTTP/1.1\r\n\r\n") 168 | go func() { 169 | ch <- s.ServeConn(rw) 170 | }() 171 | select { 172 | case err := <-ch: 173 | if err != nil { 174 | t.Fatalf("return error %s", err) 175 | } 176 | case <-time.After(100 * time.Millisecond): 177 | t.Fatalf("timeout") 178 | } 179 | if !post { 180 | t.Error("routing POST failed") 181 | } 182 | 183 | rw.r.WriteString("PUT /PUT HTTP/1.1\r\n\r\n") 184 | go func() { 185 | ch <- s.ServeConn(rw) 186 | }() 187 | select { 188 | case err := <-ch: 189 | if err != nil { 190 | t.Fatalf("return error %s", err) 191 | } 192 | case <-time.After(100 * time.Millisecond): 193 | t.Fatalf("timeout") 194 | } 195 | if !put { 196 | t.Error("routing PUT failed") 197 | } 198 | 199 | rw.r.WriteString("PATCH /PATCH HTTP/1.1\r\n\r\n") 200 | go func() { 201 | ch <- s.ServeConn(rw) 202 | }() 203 | select { 204 | case err := <-ch: 205 | if err != nil { 206 | t.Fatalf("return error %s", err) 207 | } 208 | case <-time.After(100 * time.Millisecond): 209 | t.Fatalf("timeout") 210 | } 211 | if !patch { 212 | t.Error("routing PATCH failed") 213 | } 214 | 215 | rw.r.WriteString("DELETE /DELETE HTTP/1.1\r\n\r\n") 216 | go func() { 217 | ch <- s.ServeConn(rw) 218 | }() 219 | select { 220 | case err := <-ch: 221 | if err != nil { 222 | t.Fatalf("return error %s", err) 223 | } 224 | case <-time.After(100 * time.Millisecond): 225 | t.Fatalf("timeout") 226 | } 227 | if !deleted { 228 | t.Error("routing DELETE failed") 229 | } 230 | } 231 | 232 | func TestRouterRoot(t *testing.T) { 233 | router := New() 234 | recv := catchPanic(func() { 235 | router.GET("noSlashRoot", nil) 236 | }) 237 | if recv == nil { 238 | t.Fatal("registering path not beginning with '/' did not panic") 239 | } 240 | } 241 | 242 | func TestRouterChaining(t *testing.T) { 243 | router1 := New() 244 | router2 := New() 245 | router1.NotFound = router2.Handler 246 | 247 | fooHit := false 248 | router1.POST("/foo", func(ctx *fasthttp.RequestCtx, _ Params) { 249 | fooHit = true 250 | ctx.SetStatusCode(fasthttp.StatusOK) 251 | }) 252 | 253 | barHit := false 254 | router2.POST("/bar", func(ctx *fasthttp.RequestCtx, _ Params) { 255 | barHit = true 256 | ctx.SetStatusCode(fasthttp.StatusOK) 257 | }) 258 | 259 | s := &fasthttp.Server{ 260 | Handler: router1.Handler, 261 | } 262 | 263 | rw := &readWriter{} 264 | ch := make(chan error) 265 | 266 | rw.r.WriteString("POST /foo HTTP/1.1\r\n\r\n") 267 | go func() { 268 | ch <- s.ServeConn(rw) 269 | }() 270 | select { 271 | case err := <-ch: 272 | if err != nil { 273 | t.Fatalf("return error %s", err) 274 | } 275 | case <-time.After(100 * time.Millisecond): 276 | t.Fatalf("timeout") 277 | } 278 | br := bufio.NewReader(&rw.w) 279 | var resp fasthttp.Response 280 | if err := resp.Read(br); err != nil { 281 | t.Fatalf("Unexpected error when reading response: %s", err) 282 | } 283 | if !(resp.Header.StatusCode() == fasthttp.StatusOK && fooHit) { 284 | t.Errorf("Regular routing failed with router chaining.") 285 | t.FailNow() 286 | } 287 | 288 | rw.r.WriteString("POST /bar HTTP/1.1\r\n\r\n") 289 | go func() { 290 | ch <- s.ServeConn(rw) 291 | }() 292 | select { 293 | case err := <-ch: 294 | if err != nil { 295 | t.Fatalf("return error %s", err) 296 | } 297 | case <-time.After(100 * time.Millisecond): 298 | t.Fatalf("timeout") 299 | } 300 | if err := resp.Read(br); err != nil { 301 | t.Fatalf("Unexpected error when reading response: %s", err) 302 | } 303 | if !(resp.Header.StatusCode() == fasthttp.StatusOK && barHit) { 304 | t.Errorf("Chained routing failed with router chaining.") 305 | t.FailNow() 306 | } 307 | 308 | rw.r.WriteString("POST /qax HTTP/1.1\r\n\r\n") 309 | go func() { 310 | ch <- s.ServeConn(rw) 311 | }() 312 | select { 313 | case err := <-ch: 314 | if err != nil { 315 | t.Fatalf("return error %s", err) 316 | } 317 | case <-time.After(100 * time.Millisecond): 318 | t.Fatalf("timeout") 319 | } 320 | if err := resp.Read(br); err != nil { 321 | t.Fatalf("Unexpected error when reading response: %s", err) 322 | } 323 | if !(resp.Header.StatusCode() == fasthttp.StatusNotFound) { 324 | t.Errorf("NotFound behavior failed with router chaining.") 325 | t.FailNow() 326 | } 327 | } 328 | 329 | func TestRouterOPTIONS(t *testing.T) { 330 | // TODO: because fasthttp is not support OPTIONS method now, 331 | // these test cases will be used in the future. 332 | handlerFunc := func(_ *fasthttp.RequestCtx, _ Params) {} 333 | 334 | router := New() 335 | router.POST("/path", handlerFunc) 336 | 337 | // test not allowed 338 | // * (server) 339 | s := &fasthttp.Server{ 340 | Handler: router.Handler, 341 | } 342 | 343 | rw := &readWriter{} 344 | ch := make(chan error) 345 | 346 | rw.r.WriteString("OPTIONS * HTTP/1.1\r\nHost:\r\n\r\n") 347 | go func() { 348 | ch <- s.ServeConn(rw) 349 | }() 350 | select { 351 | case err := <-ch: 352 | if err != nil { 353 | t.Fatalf("return error %s", err) 354 | } 355 | case <-time.After(100 * time.Millisecond): 356 | t.Fatalf("timeout") 357 | } 358 | br := bufio.NewReader(&rw.w) 359 | var resp fasthttp.Response 360 | if err := resp.Read(br); err != nil { 361 | t.Fatalf("Unexpected error when reading response: %s", err) 362 | } 363 | if resp.Header.StatusCode() != fasthttp.StatusOK { 364 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 365 | resp.Header.StatusCode(), resp.Header.String()) 366 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, OPTIONS" { 367 | t.Error("unexpected Allow header value: " + allow) 368 | } 369 | 370 | // path 371 | rw.r.WriteString("OPTIONS /path HTTP/1.1\r\n\r\n") 372 | go func() { 373 | ch <- s.ServeConn(rw) 374 | }() 375 | select { 376 | case err := <-ch: 377 | if err != nil { 378 | t.Fatalf("return error %s", err) 379 | } 380 | case <-time.After(100 * time.Millisecond): 381 | t.Fatalf("timeout") 382 | } 383 | if err := resp.Read(br); err != nil { 384 | t.Fatalf("Unexpected error when reading response: %s", err) 385 | } 386 | if resp.Header.StatusCode() != fasthttp.StatusOK { 387 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 388 | resp.Header.StatusCode(), resp.Header.String()) 389 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, OPTIONS" { 390 | t.Error("unexpected Allow header value: " + allow) 391 | } 392 | 393 | rw.r.WriteString("OPTIONS /doesnotexist HTTP/1.1\r\n\r\n") 394 | go func() { 395 | ch <- s.ServeConn(rw) 396 | }() 397 | select { 398 | case err := <-ch: 399 | if err != nil { 400 | t.Fatalf("return error %s", err) 401 | } 402 | case <-time.After(100 * time.Millisecond): 403 | t.Fatalf("timeout") 404 | } 405 | if err := resp.Read(br); err != nil { 406 | t.Fatalf("Unexpected error when reading response: %s", err) 407 | } 408 | if !(resp.Header.StatusCode() == fasthttp.StatusNotFound) { 409 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 410 | resp.Header.StatusCode(), resp.Header.String()) 411 | } 412 | 413 | // add another method 414 | router.GET("/path", handlerFunc) 415 | 416 | // test again 417 | // * (server) 418 | rw.r.WriteString("OPTIONS * HTTP/1.1\r\n\r\n") 419 | go func() { 420 | ch <- s.ServeConn(rw) 421 | }() 422 | select { 423 | case err := <-ch: 424 | if err != nil { 425 | t.Fatalf("return error %s", err) 426 | } 427 | case <-time.After(100 * time.Millisecond): 428 | t.Fatalf("timeout") 429 | } 430 | if err := resp.Read(br); err != nil { 431 | t.Fatalf("Unexpected error when reading response: %s", err) 432 | } 433 | if resp.Header.StatusCode() != fasthttp.StatusOK { 434 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 435 | resp.Header.StatusCode(), resp.Header.String()) 436 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { 437 | t.Error("unexpected Allow header value: " + allow) 438 | } 439 | 440 | // path 441 | rw.r.WriteString("OPTIONS /path HTTP/1.1\r\n\r\n") 442 | go func() { 443 | ch <- s.ServeConn(rw) 444 | }() 445 | select { 446 | case err := <-ch: 447 | if err != nil { 448 | t.Fatalf("return error %s", err) 449 | } 450 | case <-time.After(100 * time.Millisecond): 451 | t.Fatalf("timeout") 452 | } 453 | if err := resp.Read(br); err != nil { 454 | t.Fatalf("Unexpected error when reading response: %s", err) 455 | } 456 | if resp.Header.StatusCode() != fasthttp.StatusOK { 457 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 458 | resp.Header.StatusCode(), resp.Header.String()) 459 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { 460 | t.Error("unexpected Allow header value: " + allow) 461 | } 462 | 463 | // custom handler 464 | var custom bool 465 | router.OPTIONS("/path", func(_ *fasthttp.RequestCtx, _ Params) { 466 | custom = true 467 | }) 468 | 469 | // test again 470 | // * (server) 471 | rw.r.WriteString("OPTIONS * HTTP/1.1\r\n\r\n") 472 | go func() { 473 | ch <- s.ServeConn(rw) 474 | }() 475 | select { 476 | case err := <-ch: 477 | if err != nil { 478 | t.Fatalf("return error %s", err) 479 | } 480 | case <-time.After(100 * time.Millisecond): 481 | t.Fatalf("timeout") 482 | } 483 | if err := resp.Read(br); err != nil { 484 | t.Fatalf("Unexpected error when reading response: %s", err) 485 | } 486 | if resp.Header.StatusCode() != fasthttp.StatusOK { 487 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 488 | resp.Header.StatusCode(), resp.Header.String()) 489 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, GET, OPTIONS" && allow != "GET, POST, OPTIONS" { 490 | t.Error("unexpected Allow header value: " + allow) 491 | } 492 | if custom { 493 | t.Error("custom handler called on *") 494 | } 495 | 496 | // path 497 | rw.r.WriteString("OPTIONS /path HTTP/1.1\r\n\r\n") 498 | go func() { 499 | ch <- s.ServeConn(rw) 500 | }() 501 | select { 502 | case err := <-ch: 503 | if err != nil { 504 | t.Fatalf("return error %s", err) 505 | } 506 | case <-time.After(100 * time.Millisecond): 507 | t.Fatalf("timeout") 508 | } 509 | if err := resp.Read(br); err != nil { 510 | t.Fatalf("Unexpected error when reading response: %s", err) 511 | } 512 | if resp.Header.StatusCode() != fasthttp.StatusOK { 513 | t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", 514 | resp.Header.StatusCode(), resp.Header.String()) 515 | } 516 | if !custom { 517 | t.Error("custom handler not called") 518 | } 519 | } 520 | 521 | func TestRouterNotAllowed(t *testing.T) { 522 | handlerFunc := func(_ *fasthttp.RequestCtx, _ Params) {} 523 | 524 | router := New() 525 | router.POST("/path", handlerFunc) 526 | 527 | // Test not allowed 528 | s := &fasthttp.Server{ 529 | Handler: router.Handler, 530 | } 531 | 532 | rw := &readWriter{} 533 | ch := make(chan error) 534 | 535 | rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n") 536 | go func() { 537 | ch <- s.ServeConn(rw) 538 | }() 539 | select { 540 | case err := <-ch: 541 | if err != nil { 542 | t.Fatalf("return error %s", err) 543 | } 544 | case <-time.After(100 * time.Millisecond): 545 | t.Fatalf("timeout") 546 | } 547 | br := bufio.NewReader(&rw.w) 548 | var resp fasthttp.Response 549 | if err := resp.Read(br); err != nil { 550 | t.Fatalf("Unexpected error when reading response: %s", err) 551 | } 552 | if !(resp.Header.StatusCode() == fasthttp.StatusMethodNotAllowed) { 553 | t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", resp.Header.StatusCode(), resp.Header) 554 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, OPTIONS" { 555 | t.Error("unexpected Allow header value: " + allow) 556 | } 557 | 558 | // add another method 559 | router.DELETE("/path", handlerFunc) 560 | router.OPTIONS("/path", handlerFunc) // must be ignored 561 | 562 | // test again 563 | rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n") 564 | go func() { 565 | ch <- s.ServeConn(rw) 566 | }() 567 | select { 568 | case err := <-ch: 569 | if err != nil { 570 | t.Fatalf("return error %s", err) 571 | } 572 | case <-time.After(100 * time.Millisecond): 573 | t.Fatalf("timeout") 574 | } 575 | if err := resp.Read(br); err != nil { 576 | t.Fatalf("Unexpected error when reading response: %s", err) 577 | } 578 | if !(resp.Header.StatusCode() == fasthttp.StatusMethodNotAllowed) { 579 | t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", resp.Header.StatusCode(), resp.Header) 580 | } else if allow := string(resp.Header.Peek("Allow")); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" { 581 | t.Error("unexpected Allow header value: " + allow) 582 | } 583 | 584 | responseText := "custom method" 585 | router.MethodNotAllowed = fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) { 586 | ctx.SetStatusCode(fasthttp.StatusTeapot) 587 | ctx.Write([]byte(responseText)) 588 | }) 589 | rw.r.WriteString("GET /path HTTP/1.1\r\n\r\n") 590 | go func() { 591 | ch <- s.ServeConn(rw) 592 | }() 593 | select { 594 | case err := <-ch: 595 | if err != nil { 596 | t.Fatalf("return error %s", err) 597 | } 598 | case <-time.After(100 * time.Millisecond): 599 | t.Fatalf("timeout") 600 | } 601 | if err := resp.Read(br); err != nil { 602 | t.Fatalf("Unexpected error when reading response: %s", err) 603 | } 604 | if !bytes.Equal(resp.Body(), []byte(responseText)) { 605 | t.Errorf("unexpected response got %q want %q", string(resp.Body()), responseText) 606 | } 607 | if resp.Header.StatusCode() != fasthttp.StatusTeapot { 608 | t.Errorf("unexpected response code %d want %d", resp.Header.StatusCode(), fasthttp.StatusTeapot) 609 | } 610 | if allow := string(resp.Header.Peek("Allow")); allow != "POST, DELETE, OPTIONS" && allow != "DELETE, POST, OPTIONS" { 611 | t.Error("unexpected Allow header value: " + allow) 612 | } 613 | } 614 | 615 | func TestRouterNotFound(t *testing.T) { 616 | handlerFunc := func(_ *fasthttp.RequestCtx, _ Params) {} 617 | 618 | router := New() 619 | router.GET("/path", handlerFunc) 620 | router.GET("/dir/", handlerFunc) 621 | router.GET("/", handlerFunc) 622 | 623 | testRoutes := []struct { 624 | route string 625 | code int 626 | }{ 627 | {"/path/", 301}, // TSR -/ 628 | {"/dir", 301}, // TSR +/ 629 | {"/", 200}, // TSR +/ 630 | {"/PATH", 301}, // Fixed Case 631 | {"/DIR", 301}, // Fixed Case 632 | {"/PATH/", 301}, // Fixed Case -/ 633 | {"/DIR/", 301}, // Fixed Case +/ 634 | {"/../path", 200}, // CleanPath 635 | {"/nope", 404}, // NotFound 636 | } 637 | 638 | s := &fasthttp.Server{ 639 | Handler: router.Handler, 640 | } 641 | 642 | rw := &readWriter{} 643 | br := bufio.NewReader(&rw.w) 644 | var resp fasthttp.Response 645 | ch := make(chan error) 646 | for _, tr := range testRoutes { 647 | rw.r.WriteString(fmt.Sprintf("GET %s HTTP/1.1\r\n\r\n", tr.route)) 648 | go func() { 649 | ch <- s.ServeConn(rw) 650 | }() 651 | select { 652 | case err := <-ch: 653 | if err != nil { 654 | t.Fatalf("return error %s", err) 655 | } 656 | case <-time.After(100 * time.Millisecond): 657 | t.Fatalf("timeout") 658 | } 659 | if err := resp.Read(br); err != nil { 660 | t.Fatalf("Unexpected error when reading response: %s", err) 661 | } 662 | if !(resp.Header.StatusCode() == tr.code) { 663 | t.Errorf("NotFound handling route %s failed: Code=%d want=%d", 664 | tr.route, resp.Header.StatusCode(), tr.code) 665 | } 666 | } 667 | 668 | // Test custom not found handler 669 | var notFound bool 670 | router.NotFound = fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) { 671 | ctx.SetStatusCode(404) 672 | notFound = true 673 | }) 674 | rw.r.WriteString("GET /nope HTTP/1.1\r\n\r\n") 675 | go func() { 676 | ch <- s.ServeConn(rw) 677 | }() 678 | select { 679 | case err := <-ch: 680 | if err != nil { 681 | t.Fatalf("return error %s", err) 682 | } 683 | case <-time.After(100 * time.Millisecond): 684 | t.Fatalf("timeout") 685 | } 686 | if err := resp.Read(br); err != nil { 687 | t.Fatalf("Unexpected error when reading response: %s", err) 688 | } 689 | if !(resp.Header.StatusCode() == 404 && notFound == true) { 690 | t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", resp.Header.StatusCode(), string(resp.Header.Peek("Location"))) 691 | } 692 | 693 | // Test other method than GET (want 307 instead of 301) 694 | router.PATCH("/path", handlerFunc) 695 | rw.r.WriteString("PATCH /path/ HTTP/1.1\r\n\r\n") 696 | go func() { 697 | ch <- s.ServeConn(rw) 698 | }() 699 | select { 700 | case err := <-ch: 701 | if err != nil { 702 | t.Fatalf("return error %s", err) 703 | } 704 | case <-time.After(100 * time.Millisecond): 705 | t.Fatalf("timeout") 706 | } 707 | if err := resp.Read(br); err != nil { 708 | t.Fatalf("Unexpected error when reading response: %s", err) 709 | } 710 | if !(resp.Header.StatusCode() == 307) { 711 | t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", resp.Header.StatusCode(), string(resp.Header.Peek("Location"))) 712 | } 713 | 714 | // Test special case where no node for the prefix "/" exists 715 | router = New() 716 | router.GET("/a", handlerFunc) 717 | s.Handler = router.Handler 718 | rw.r.WriteString("GET / HTTP/1.1\r\n\r\n") 719 | go func() { 720 | ch <- s.ServeConn(rw) 721 | }() 722 | select { 723 | case err := <-ch: 724 | if err != nil { 725 | t.Fatalf("return error %s", err) 726 | } 727 | case <-time.After(100 * time.Millisecond): 728 | t.Fatalf("timeout") 729 | } 730 | if err := resp.Read(br); err != nil { 731 | t.Fatalf("Unexpected error when reading response: %s", err) 732 | } 733 | if !(resp.Header.StatusCode() == 404) { 734 | t.Errorf("NotFound handling route / failed: Code=%d", resp.Header.StatusCode()) 735 | } 736 | } 737 | 738 | func TestRouterPanicHandler(t *testing.T) { 739 | router := New() 740 | panicHandled := false 741 | 742 | router.PanicHandler = func(ctx *fasthttp.RequestCtx, p interface{}) { 743 | panicHandled = true 744 | } 745 | 746 | router.Handle("PUT", "/user/:name", func(_ *fasthttp.RequestCtx, _ Params) { 747 | panic("oops!") 748 | }) 749 | 750 | defer func() { 751 | if rcv := recover(); rcv != nil { 752 | t.Fatal("handling panic failed") 753 | } 754 | }() 755 | 756 | s := &fasthttp.Server{ 757 | Handler: router.Handler, 758 | } 759 | 760 | rw := &readWriter{} 761 | ch := make(chan error) 762 | 763 | rw.r.WriteString(string("PUT /user/gopher HTTP/1.1\r\n\r\n")) 764 | go func() { 765 | ch <- s.ServeConn(rw) 766 | }() 767 | select { 768 | case err := <-ch: 769 | if err != nil { 770 | t.Fatalf("return error %s", err) 771 | } 772 | case <-time.After(100 * time.Millisecond): 773 | t.Fatalf("timeout") 774 | } 775 | 776 | if !panicHandled { 777 | t.Fatal("simulating failed") 778 | } 779 | } 780 | 781 | func TestRouterLookup(t *testing.T) { 782 | routed := false 783 | wantHandle := func(_ *fasthttp.RequestCtx, _ Params) { 784 | routed = true 785 | } 786 | wantParams := Params{Param{"name", "gopher"}} 787 | 788 | router := New() 789 | 790 | // try empty router first 791 | handle, _, tsr := router.Lookup("GET", "/nope") 792 | if handle != nil { 793 | t.Fatalf("Got handle for unregistered pattern: %v", handle) 794 | } 795 | if tsr { 796 | t.Error("Got wrong TSR recommendation!") 797 | } 798 | 799 | // insert route and try again 800 | router.GET("/user/:name", wantHandle) 801 | 802 | handle, params, tsr := router.Lookup("GET", "/user/gopher") 803 | if handle == nil { 804 | t.Fatal("Got no handle!") 805 | } else { 806 | handle(nil, nil) 807 | if !routed { 808 | t.Fatal("Routing failed!") 809 | } 810 | } 811 | 812 | if !reflect.DeepEqual(params, wantParams) { 813 | t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params) 814 | } 815 | 816 | handle, _, tsr = router.Lookup("GET", "/user/gopher/") 817 | if handle != nil { 818 | t.Fatalf("Got handle for unregistered pattern: %v", handle) 819 | } 820 | if !tsr { 821 | t.Error("Got no TSR recommendation!") 822 | } 823 | 824 | handle, _, tsr = router.Lookup("GET", "/nope") 825 | if handle != nil { 826 | t.Fatalf("Got handle for unregistered pattern: %v", handle) 827 | } 828 | if tsr { 829 | t.Error("Got wrong TSR recommendation!") 830 | } 831 | } 832 | 833 | type mockFileSystem struct { 834 | opened bool 835 | } 836 | 837 | func (mfs *mockFileSystem) Open(name string) (http.File, error) { 838 | mfs.opened = true 839 | return nil, errors.New("this is just a mock") 840 | } 841 | 842 | func TestRouterServeFiles(t *testing.T) { 843 | router := New() 844 | 845 | recv := catchPanic(func() { 846 | router.ServeFiles("/noFilepath", os.TempDir()) 847 | }) 848 | if recv == nil { 849 | t.Fatal("registering path not ending with '*filepath' did not panic") 850 | } 851 | body := []byte("fake ico") 852 | ioutil.WriteFile(os.TempDir()+"/favicon.ico", body, 0644) 853 | 854 | router.ServeFiles("/*filepath", os.TempDir()) 855 | 856 | s := &fasthttp.Server{ 857 | Handler: router.Handler, 858 | } 859 | 860 | rw := &readWriter{} 861 | ch := make(chan error) 862 | 863 | rw.r.WriteString(string("GET /favicon.ico HTTP/1.1\r\n\r\n")) 864 | go func() { 865 | ch <- s.ServeConn(rw) 866 | }() 867 | select { 868 | case err := <-ch: 869 | if err != nil { 870 | t.Fatalf("return error %s", err) 871 | } 872 | case <-time.After(100 * time.Millisecond): 873 | t.Fatalf("timeout") 874 | } 875 | 876 | br := bufio.NewReader(&rw.w) 877 | var resp fasthttp.Response 878 | if err := resp.Read(br); err != nil { 879 | t.Fatalf("Unexpected error when reading response: %s", err) 880 | } 881 | if resp.Header.StatusCode() != 200 { 882 | t.Fatalf("Unexpected status code %d. Expected %d", resp.Header.StatusCode(), 423) 883 | } 884 | if !bytes.Equal(resp.Body(), body) { 885 | t.Fatalf("Unexpected body %q. Expected %q", resp.Body(), string(body)) 886 | } 887 | } 888 | 889 | type readWriter struct { 890 | net.Conn 891 | r bytes.Buffer 892 | w bytes.Buffer 893 | } 894 | 895 | var zeroTCPAddr = &net.TCPAddr{ 896 | IP: net.IPv4zero, 897 | } 898 | 899 | func (rw *readWriter) Close() error { 900 | return nil 901 | } 902 | 903 | func (rw *readWriter) Read(b []byte) (int, error) { 904 | return rw.r.Read(b) 905 | } 906 | 907 | func (rw *readWriter) Write(b []byte) (int, error) { 908 | return rw.w.Write(b) 909 | } 910 | 911 | func (rw *readWriter) RemoteAddr() net.Addr { 912 | return zeroTCPAddr 913 | } 914 | 915 | func (rw *readWriter) LocalAddr() net.Addr { 916 | return zeroTCPAddr 917 | } 918 | 919 | func (rw *readWriter) SetReadDeadline(t time.Time) error { 920 | return nil 921 | } 922 | 923 | func (rw *readWriter) SetWriteDeadline(t time.Time) error { 924 | return nil 925 | } 926 | -------------------------------------------------------------------------------- /tree.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be found 3 | // in the LICENSE file. 4 | 5 | package fasthttprouter 6 | 7 | import ( 8 | "strings" 9 | "unicode" 10 | "unicode/utf8" 11 | ) 12 | 13 | func min(a, b int) int { 14 | if a <= b { 15 | return a 16 | } 17 | return b 18 | } 19 | 20 | func countParams(path string) uint8 { 21 | var n uint 22 | for i := 0; i < len(path); i++ { 23 | if path[i] != ':' && path[i] != '*' { 24 | continue 25 | } 26 | n++ 27 | } 28 | if n >= 255 { 29 | return 255 30 | } 31 | return uint8(n) 32 | } 33 | 34 | type nodeType uint8 35 | 36 | const ( 37 | static nodeType = iota // default 38 | root 39 | param 40 | catchAll 41 | ) 42 | 43 | type node struct { 44 | path string 45 | wildChild bool 46 | nType nodeType 47 | maxParams uint8 48 | indices string 49 | children []*node 50 | handle Handle 51 | priority uint32 52 | } 53 | 54 | // increments priority of the given child and reorders if necessary 55 | func (n *node) incrementChildPrio(pos int) int { 56 | n.children[pos].priority++ 57 | prio := n.children[pos].priority 58 | 59 | // adjust position (move to front) 60 | newPos := pos 61 | for newPos > 0 && n.children[newPos-1].priority < prio { 62 | // swap node positions 63 | tmpN := n.children[newPos-1] 64 | n.children[newPos-1] = n.children[newPos] 65 | n.children[newPos] = tmpN 66 | 67 | newPos-- 68 | } 69 | 70 | // build new index char string 71 | if newPos != pos { 72 | n.indices = n.indices[:newPos] + // unchanged prefix, might be empty 73 | n.indices[pos:pos+1] + // the index char we move 74 | n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos' 75 | } 76 | 77 | return newPos 78 | } 79 | 80 | // addRoute adds a node with the given handle to the path. 81 | // Not concurrency-safe! 82 | func (n *node) addRoute(path string, handle Handle) { 83 | fullPath := path 84 | n.priority++ 85 | numParams := countParams(path) 86 | 87 | // non-empty tree 88 | if len(n.path) > 0 || len(n.children) > 0 { 89 | walk: 90 | for { 91 | // Update maxParams of the current node 92 | if numParams > n.maxParams { 93 | n.maxParams = numParams 94 | } 95 | 96 | // Find the longest common prefix. 97 | // This also implies that the common prefix contains no ':' or '*' 98 | // since the existing key can't contain those chars. 99 | i := 0 100 | max := min(len(path), len(n.path)) 101 | for i < max && path[i] == n.path[i] { 102 | i++ 103 | } 104 | 105 | // Split edge 106 | if i < len(n.path) { 107 | child := node{ 108 | path: n.path[i:], 109 | wildChild: n.wildChild, 110 | nType: static, 111 | indices: n.indices, 112 | children: n.children, 113 | handle: n.handle, 114 | priority: n.priority - 1, 115 | } 116 | 117 | // Update maxParams (max of all children) 118 | for i := range child.children { 119 | if child.children[i].maxParams > child.maxParams { 120 | child.maxParams = child.children[i].maxParams 121 | } 122 | } 123 | 124 | n.children = []*node{&child} 125 | // []byte for proper unicode char conversion, see #65 126 | n.indices = string([]byte{n.path[i]}) 127 | n.path = path[:i] 128 | n.handle = nil 129 | n.wildChild = false 130 | } 131 | 132 | // Make new node a child of this node 133 | if i < len(path) { 134 | path = path[i:] 135 | 136 | if n.wildChild { 137 | n = n.children[0] 138 | n.priority++ 139 | 140 | // Update maxParams of the child node 141 | if numParams > n.maxParams { 142 | n.maxParams = numParams 143 | } 144 | numParams-- 145 | 146 | // Check if the wildcard matches 147 | if len(path) >= len(n.path) && n.path == path[:len(n.path)] { 148 | // check for longer wildcard, e.g. :name and :names 149 | if len(n.path) >= len(path) || path[len(n.path)] == '/' { 150 | continue walk 151 | } 152 | } 153 | 154 | panic("path segment '" + path + 155 | "' conflicts with existing wildcard '" + n.path + 156 | "' in path '" + fullPath + "'") 157 | } 158 | 159 | c := path[0] 160 | 161 | // slash after param 162 | if n.nType == param && c == '/' && len(n.children) == 1 { 163 | n = n.children[0] 164 | n.priority++ 165 | continue walk 166 | } 167 | 168 | // Check if a child with the next path byte exists 169 | for i := 0; i < len(n.indices); i++ { 170 | if c == n.indices[i] { 171 | i = n.incrementChildPrio(i) 172 | n = n.children[i] 173 | continue walk 174 | } 175 | } 176 | 177 | // Otherwise insert it 178 | if c != ':' && c != '*' { 179 | // []byte for proper unicode char conversion, see #65 180 | n.indices += string([]byte{c}) 181 | child := &node{ 182 | maxParams: numParams, 183 | } 184 | n.children = append(n.children, child) 185 | n.incrementChildPrio(len(n.indices) - 1) 186 | n = child 187 | } 188 | n.insertChild(numParams, path, fullPath, handle) 189 | return 190 | 191 | } else if i == len(path) { // Make node a (in-path) leaf 192 | if n.handle != nil { 193 | panic("a handle is already registered for path '" + fullPath + "'") 194 | } 195 | n.handle = handle 196 | } 197 | return 198 | } 199 | } else { // Empty tree 200 | n.insertChild(numParams, path, fullPath, handle) 201 | n.nType = root 202 | } 203 | } 204 | 205 | func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) { 206 | var offset int // already handled bytes of the path 207 | 208 | // find prefix until first wildcard (beginning with ':'' or '*'') 209 | for i, max := 0, len(path); numParams > 0; i++ { 210 | c := path[i] 211 | if c != ':' && c != '*' { 212 | continue 213 | } 214 | 215 | // find wildcard end (either '/' or path end) 216 | end := i + 1 217 | for end < max && path[end] != '/' { 218 | switch path[end] { 219 | // the wildcard name must not contain ':' and '*' 220 | case ':', '*': 221 | panic("only one wildcard per path segment is allowed, has: '" + 222 | path[i:] + "' in path '" + fullPath + "'") 223 | default: 224 | end++ 225 | } 226 | } 227 | 228 | // check if this Node existing children which would be 229 | // unreachable if we insert the wildcard here 230 | if len(n.children) > 0 { 231 | panic("wildcard route '" + path[i:end] + 232 | "' conflicts with existing children in path '" + fullPath + "'") 233 | } 234 | 235 | // check if the wildcard has a name 236 | if end-i < 2 { 237 | panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") 238 | } 239 | 240 | if c == ':' { // param 241 | // split path at the beginning of the wildcard 242 | if i > 0 { 243 | n.path = path[offset:i] 244 | offset = i 245 | } 246 | 247 | child := &node{ 248 | nType: param, 249 | maxParams: numParams, 250 | } 251 | n.children = []*node{child} 252 | n.wildChild = true 253 | n = child 254 | n.priority++ 255 | numParams-- 256 | 257 | // if the path doesn't end with the wildcard, then there 258 | // will be another non-wildcard subpath starting with '/' 259 | if end < max { 260 | n.path = path[offset:end] 261 | offset = end 262 | 263 | child := &node{ 264 | maxParams: numParams, 265 | priority: 1, 266 | } 267 | n.children = []*node{child} 268 | n = child 269 | } 270 | 271 | } else { // catchAll 272 | if end != max || numParams > 1 { 273 | panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") 274 | } 275 | 276 | if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { 277 | panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") 278 | } 279 | 280 | // currently fixed width 1 for '/' 281 | i-- 282 | if path[i] != '/' { 283 | panic("no / before catch-all in path '" + fullPath + "'") 284 | } 285 | 286 | n.path = path[offset:i] 287 | 288 | // first node: catchAll node with empty path 289 | child := &node{ 290 | wildChild: true, 291 | nType: catchAll, 292 | maxParams: 1, 293 | } 294 | n.children = []*node{child} 295 | n.indices = string(path[i]) 296 | n = child 297 | n.priority++ 298 | 299 | // second node: node holding the variable 300 | child = &node{ 301 | path: path[i:], 302 | nType: catchAll, 303 | maxParams: 1, 304 | handle: handle, 305 | priority: 1, 306 | } 307 | n.children = []*node{child} 308 | 309 | return 310 | } 311 | } 312 | 313 | // insert remaining path part and handle to the leaf 314 | n.path = path[offset:] 315 | n.handle = handle 316 | } 317 | 318 | // Returns the handle registered with the given path (key). The values of 319 | // wildcards are saved to a map. 320 | // If no handle can be found, a TSR (trailing slash redirect) recommendation is 321 | // made if a handle exists with an extra (without the) trailing slash for the 322 | // given path. 323 | func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) { 324 | walk: // outer loop for walking the tree 325 | for { 326 | if len(path) > len(n.path) { 327 | if path[:len(n.path)] == n.path { 328 | path = path[len(n.path):] 329 | // If this node does not have a wildcard (param or catchAll) 330 | // child, we can just look up the next child node and continue 331 | // to walk down the tree 332 | if !n.wildChild { 333 | c := path[0] 334 | for i := 0; i < len(n.indices); i++ { 335 | if c == n.indices[i] { 336 | n = n.children[i] 337 | continue walk 338 | } 339 | } 340 | 341 | // Nothing found. 342 | // We can recommend to redirect to the same URL without a 343 | // trailing slash if a leaf exists for that path. 344 | tsr = (path == "/" && n.handle != nil) 345 | return 346 | 347 | } 348 | 349 | // handle wildcard child 350 | n = n.children[0] 351 | switch n.nType { 352 | case param: 353 | // find param end (either '/' or path end) 354 | end := 0 355 | for end < len(path) && path[end] != '/' { 356 | end++ 357 | } 358 | 359 | // save param value 360 | if p == nil { 361 | // lazy allocation 362 | p = make(Params, 0, n.maxParams) 363 | } 364 | i := len(p) 365 | p = p[:i+1] // expand slice within preallocated capacity 366 | p[i].Key = n.path[1:] 367 | p[i].Value = path[:end] 368 | 369 | // we need to go deeper! 370 | if end < len(path) { 371 | if len(n.children) > 0 { 372 | path = path[end:] 373 | n = n.children[0] 374 | continue walk 375 | } 376 | 377 | // ... but we can't 378 | tsr = (len(path) == end+1) 379 | return 380 | } 381 | 382 | if handle = n.handle; handle != nil { 383 | return 384 | } else if len(n.children) == 1 { 385 | // No handle found. Check if a handle for this path + a 386 | // trailing slash exists for TSR recommendation 387 | n = n.children[0] 388 | tsr = (n.path == "/" && n.handle != nil) 389 | } 390 | 391 | return 392 | 393 | case catchAll: 394 | // save param value 395 | if p == nil { 396 | // lazy allocation 397 | p = make(Params, 0, n.maxParams) 398 | } 399 | i := len(p) 400 | p = p[:i+1] // expand slice within preallocated capacity 401 | p[i].Key = n.path[2:] 402 | p[i].Value = path 403 | 404 | handle = n.handle 405 | return 406 | 407 | default: 408 | panic("invalid node type") 409 | } 410 | } 411 | } else if path == n.path { 412 | // We should have reached the node containing the handle. 413 | // Check if this node has a handle registered. 414 | if handle = n.handle; handle != nil { 415 | return 416 | } 417 | 418 | if path == "/" && n.wildChild && n.nType != root { 419 | tsr = true 420 | return 421 | } 422 | 423 | // No handle found. Check if a handle for this path + a 424 | // trailing slash exists for trailing slash recommendation 425 | for i := 0; i < len(n.indices); i++ { 426 | if n.indices[i] == '/' { 427 | n = n.children[i] 428 | tsr = (len(n.path) == 1 && n.handle != nil) || 429 | (n.nType == catchAll && n.children[0].handle != nil) 430 | return 431 | } 432 | } 433 | 434 | return 435 | } 436 | 437 | // Nothing found. We can recommend to redirect to the same URL with an 438 | // extra trailing slash if a leaf exists for that path 439 | tsr = (path == "/") || 440 | (len(n.path) == len(path)+1 && n.path[len(path)] == '/' && 441 | path == n.path[:len(n.path)-1] && n.handle != nil) 442 | return 443 | } 444 | } 445 | 446 | // Makes a case-insensitive lookup of the given path and tries to find a handler. 447 | // It can optionally also fix trailing slashes. 448 | // It returns the case-corrected path and a bool indicating whether the lookup 449 | // was successful. 450 | func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) { 451 | return n.findCaseInsensitivePathRec( 452 | path, 453 | strings.ToLower(path), 454 | make([]byte, 0, len(path)+1), // preallocate enough memory for new path 455 | [4]byte{}, // empty rune buffer 456 | fixTrailingSlash, 457 | ) 458 | } 459 | 460 | // shift bytes in array by n bytes left 461 | func shiftNRuneBytes(rb [4]byte, n int) [4]byte { 462 | switch n { 463 | case 0: 464 | return rb 465 | case 1: 466 | return [4]byte{rb[1], rb[2], rb[3], 0} 467 | case 2: 468 | return [4]byte{rb[2], rb[3]} 469 | case 3: 470 | return [4]byte{rb[3]} 471 | default: 472 | return [4]byte{} 473 | } 474 | } 475 | 476 | // recursive case-insensitive lookup function used by n.findCaseInsensitivePath 477 | func (n *node) findCaseInsensitivePathRec(path, loPath string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) { 478 | loNPath := strings.ToLower(n.path) 479 | 480 | walk: // outer loop for walking the tree 481 | for len(loPath) >= len(loNPath) && (len(loNPath) == 0 || loPath[1:len(loNPath)] == loNPath[1:]) { 482 | // add common path to result 483 | ciPath = append(ciPath, n.path...) 484 | 485 | if path = path[len(n.path):]; len(path) > 0 { 486 | loOld := loPath 487 | loPath = loPath[len(loNPath):] 488 | 489 | // If this node does not have a wildcard (param or catchAll) child, 490 | // we can just look up the next child node and continue to walk down 491 | // the tree 492 | if !n.wildChild { 493 | // skip rune bytes already processed 494 | rb = shiftNRuneBytes(rb, len(loNPath)) 495 | 496 | if rb[0] != 0 { 497 | // old rune not finished 498 | for i := 0; i < len(n.indices); i++ { 499 | if n.indices[i] == rb[0] { 500 | // continue with child node 501 | n = n.children[i] 502 | loNPath = strings.ToLower(n.path) 503 | continue walk 504 | } 505 | } 506 | } else { 507 | // process a new rune 508 | var rv rune 509 | 510 | // find rune start 511 | // runes are up to 4 byte long, 512 | // -4 would definitely be another rune 513 | var off int 514 | for max := min(len(loNPath), 3); off < max; off++ { 515 | if i := len(loNPath) - off; utf8.RuneStart(loOld[i]) { 516 | // read rune from cached lowercase path 517 | rv, _ = utf8.DecodeRuneInString(loOld[i:]) 518 | break 519 | } 520 | } 521 | 522 | // calculate lowercase bytes of current rune 523 | utf8.EncodeRune(rb[:], rv) 524 | // skipp already processed bytes 525 | rb = shiftNRuneBytes(rb, off) 526 | 527 | for i := 0; i < len(n.indices); i++ { 528 | // lowercase matches 529 | if n.indices[i] == rb[0] { 530 | // must use a recursive approach since both the 531 | // uppercase byte and the lowercase byte might exist 532 | // as an index 533 | if out, found := n.children[i].findCaseInsensitivePathRec( 534 | path, loPath, ciPath, rb, fixTrailingSlash, 535 | ); found { 536 | return out, true 537 | } 538 | break 539 | } 540 | } 541 | 542 | // same for uppercase rune, if it differs 543 | if up := unicode.ToUpper(rv); up != rv { 544 | utf8.EncodeRune(rb[:], up) 545 | rb = shiftNRuneBytes(rb, off) 546 | 547 | for i := 0; i < len(n.indices); i++ { 548 | // uppercase matches 549 | if n.indices[i] == rb[0] { 550 | // continue with child node 551 | n = n.children[i] 552 | loNPath = strings.ToLower(n.path) 553 | continue walk 554 | } 555 | } 556 | } 557 | } 558 | 559 | // Nothing found. We can recommend to redirect to the same URL 560 | // without a trailing slash if a leaf exists for that path 561 | return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil) 562 | } 563 | 564 | n = n.children[0] 565 | switch n.nType { 566 | case param: 567 | // find param end (either '/' or path end) 568 | k := 0 569 | for k < len(path) && path[k] != '/' { 570 | k++ 571 | } 572 | 573 | // add param value to case insensitive path 574 | ciPath = append(ciPath, path[:k]...) 575 | 576 | // we need to go deeper! 577 | if k < len(path) { 578 | if len(n.children) > 0 { 579 | // continue with child node 580 | n = n.children[0] 581 | loNPath = strings.ToLower(n.path) 582 | loPath = loPath[k:] 583 | path = path[k:] 584 | continue 585 | } 586 | 587 | // ... but we can't 588 | if fixTrailingSlash && len(path) == k+1 { 589 | return ciPath, true 590 | } 591 | return ciPath, false 592 | } 593 | 594 | if n.handle != nil { 595 | return ciPath, true 596 | } else if fixTrailingSlash && len(n.children) == 1 { 597 | // No handle found. Check if a handle for this path + a 598 | // trailing slash exists 599 | n = n.children[0] 600 | if n.path == "/" && n.handle != nil { 601 | return append(ciPath, '/'), true 602 | } 603 | } 604 | return ciPath, false 605 | 606 | case catchAll: 607 | return append(ciPath, path...), true 608 | 609 | default: 610 | panic("invalid node type") 611 | } 612 | } else { 613 | // We should have reached the node containing the handle. 614 | // Check if this node has a handle registered. 615 | if n.handle != nil { 616 | return ciPath, true 617 | } 618 | 619 | // No handle found. 620 | // Try to fix the path by adding a trailing slash 621 | if fixTrailingSlash { 622 | for i := 0; i < len(n.indices); i++ { 623 | if n.indices[i] == '/' { 624 | n = n.children[i] 625 | if (len(n.path) == 1 && n.handle != nil) || 626 | (n.nType == catchAll && n.children[0].handle != nil) { 627 | return append(ciPath, '/'), true 628 | } 629 | return ciPath, false 630 | } 631 | } 632 | } 633 | return ciPath, false 634 | } 635 | } 636 | 637 | // Nothing found. 638 | // Try to fix the path by adding / removing a trailing slash 639 | if fixTrailingSlash { 640 | if path == "/" { 641 | return ciPath, true 642 | } 643 | if len(loPath)+1 == len(loNPath) && loNPath[len(loPath)] == '/' && 644 | loPath[1:] == loNPath[1:len(loPath)] && n.handle != nil { 645 | return append(ciPath, n.path...), true 646 | } 647 | } 648 | return ciPath, false 649 | } 650 | -------------------------------------------------------------------------------- /tree_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Julien Schmidt. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be found 3 | // in the LICENSE file. 4 | 5 | package fasthttprouter 6 | 7 | import ( 8 | "fmt" 9 | "reflect" 10 | "strings" 11 | "testing" 12 | 13 | "github.com/valyala/fasthttp" 14 | ) 15 | 16 | func printChildren(n *node, prefix string) { 17 | fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handle, n.wildChild, n.nType) 18 | for l := len(n.path); l > 0; l-- { 19 | prefix += " " 20 | } 21 | for _, child := range n.children { 22 | printChildren(child, prefix) 23 | } 24 | } 25 | 26 | // Used as a workaround since we can't compare functions or their addresses 27 | var fakeHandlerValue string 28 | 29 | func fakeHandler(val string) Handle { 30 | return func(*fasthttp.RequestCtx, Params) { 31 | fakeHandlerValue = val 32 | } 33 | } 34 | 35 | type testRequests []struct { 36 | path string 37 | nilHandler bool 38 | route string 39 | ps Params 40 | } 41 | 42 | func checkRequests(t *testing.T, tree *node, requests testRequests) { 43 | for _, request := range requests { 44 | handler, ps, _ := tree.getValue(request.path) 45 | 46 | if handler == nil { 47 | if !request.nilHandler { 48 | t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path) 49 | } 50 | } else if request.nilHandler { 51 | t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path) 52 | } else { 53 | handler(nil, nil) 54 | if fakeHandlerValue != request.route { 55 | t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route) 56 | } 57 | } 58 | 59 | if !reflect.DeepEqual(ps, request.ps) { 60 | t.Errorf("Params mismatch for route '%s'", request.path) 61 | } 62 | } 63 | } 64 | 65 | func checkPriorities(t *testing.T, n *node) uint32 { 66 | var prio uint32 67 | for i := range n.children { 68 | prio += checkPriorities(t, n.children[i]) 69 | } 70 | 71 | if n.handle != nil { 72 | prio++ 73 | } 74 | 75 | if n.priority != prio { 76 | t.Errorf( 77 | "priority mismatch for node '%s': is %d, should be %d", 78 | n.path, n.priority, prio, 79 | ) 80 | } 81 | 82 | return prio 83 | } 84 | 85 | func checkMaxParams(t *testing.T, n *node) uint8 { 86 | var maxParams uint8 87 | for i := range n.children { 88 | params := checkMaxParams(t, n.children[i]) 89 | if params > maxParams { 90 | maxParams = params 91 | } 92 | } 93 | if n.nType > root && !n.wildChild { 94 | maxParams++ 95 | } 96 | 97 | if n.maxParams != maxParams { 98 | t.Errorf( 99 | "maxParams mismatch for node '%s': is %d, should be %d", 100 | n.path, n.maxParams, maxParams, 101 | ) 102 | } 103 | 104 | return maxParams 105 | } 106 | 107 | func TestCountParams(t *testing.T) { 108 | if countParams("/path/:param1/static/*catch-all") != 2 { 109 | t.Fail() 110 | } 111 | if countParams(strings.Repeat("/:param", 256)) != 255 { 112 | t.Fail() 113 | } 114 | } 115 | 116 | func TestTreeAddAndGet(t *testing.T) { 117 | tree := &node{} 118 | 119 | routes := [...]string{ 120 | "/hi", 121 | "/contact", 122 | "/co", 123 | "/c", 124 | "/a", 125 | "/ab", 126 | "/doc/", 127 | "/doc/go_faq.html", 128 | "/doc/go1.html", 129 | "/α", 130 | "/β", 131 | } 132 | for _, route := range routes { 133 | tree.addRoute(route, fakeHandler(route)) 134 | } 135 | 136 | //printChildren(tree, "") 137 | 138 | checkRequests(t, tree, testRequests{ 139 | {"/a", false, "/a", nil}, 140 | {"/", true, "", nil}, 141 | {"/hi", false, "/hi", nil}, 142 | {"/contact", false, "/contact", nil}, 143 | {"/co", false, "/co", nil}, 144 | {"/con", true, "", nil}, // key mismatch 145 | {"/cona", true, "", nil}, // key mismatch 146 | {"/no", true, "", nil}, // no matching child 147 | {"/ab", false, "/ab", nil}, 148 | {"/α", false, "/α", nil}, 149 | {"/β", false, "/β", nil}, 150 | }) 151 | 152 | checkPriorities(t, tree) 153 | checkMaxParams(t, tree) 154 | } 155 | 156 | func TestTreeWildcard(t *testing.T) { 157 | tree := &node{} 158 | 159 | routes := [...]string{ 160 | "/", 161 | "/cmd/:tool/:sub", 162 | "/cmd/:tool/", 163 | "/src/*filepath", 164 | "/search/", 165 | "/search/:query", 166 | "/user_:name", 167 | "/user_:name/about", 168 | "/files/:dir/*filepath", 169 | "/doc/", 170 | "/doc/go_faq.html", 171 | "/doc/go1.html", 172 | "/info/:user/public", 173 | "/info/:user/project/:project", 174 | } 175 | for _, route := range routes { 176 | tree.addRoute(route, fakeHandler(route)) 177 | } 178 | 179 | //printChildren(tree, "") 180 | 181 | checkRequests(t, tree, testRequests{ 182 | {"/", false, "/", nil}, 183 | {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}}, 184 | {"/cmd/test", true, "", Params{Param{"tool", "test"}}}, 185 | {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}}, 186 | {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}}, 187 | {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, 188 | {"/search/", false, "/search/", nil}, 189 | {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, 190 | {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, 191 | {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, 192 | {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}}, 193 | {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}}, 194 | {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}}, 195 | {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}}, 196 | }) 197 | 198 | checkPriorities(t, tree) 199 | checkMaxParams(t, tree) 200 | } 201 | 202 | func catchPanic(testFunc func()) (recv interface{}) { 203 | defer func() { 204 | recv = recover() 205 | }() 206 | 207 | testFunc() 208 | return 209 | } 210 | 211 | type testRoute struct { 212 | path string 213 | conflict bool 214 | } 215 | 216 | func testRoutes(t *testing.T, routes []testRoute) { 217 | tree := &node{} 218 | 219 | for _, route := range routes { 220 | recv := catchPanic(func() { 221 | tree.addRoute(route.path, nil) 222 | }) 223 | 224 | if route.conflict { 225 | if recv == nil { 226 | t.Errorf("no panic for conflicting route '%s'", route.path) 227 | } 228 | } else if recv != nil { 229 | t.Errorf("unexpected panic for route '%s': %v", route.path, recv) 230 | } 231 | } 232 | 233 | //printChildren(tree, "") 234 | } 235 | 236 | func TestTreeWildcardConflict(t *testing.T) { 237 | routes := []testRoute{ 238 | {"/cmd/:tool/:sub", false}, 239 | {"/cmd/vet", true}, 240 | {"/src/*filepath", false}, 241 | {"/src/*filepathx", true}, 242 | {"/src/", true}, 243 | {"/src1/", false}, 244 | {"/src1/*filepath", true}, 245 | {"/src2*filepath", true}, 246 | {"/search/:query", false}, 247 | {"/search/invalid", true}, 248 | {"/user_:name", false}, 249 | {"/user_x", true}, 250 | {"/user_:name", false}, 251 | {"/id:id", false}, 252 | {"/id/:id", true}, 253 | } 254 | testRoutes(t, routes) 255 | } 256 | 257 | func TestTreeChildConflict(t *testing.T) { 258 | routes := []testRoute{ 259 | {"/cmd/vet", false}, 260 | {"/cmd/:tool/:sub", true}, 261 | {"/src/AUTHORS", false}, 262 | {"/src/*filepath", true}, 263 | {"/user_x", false}, 264 | {"/user_:name", true}, 265 | {"/id/:id", false}, 266 | {"/id:id", true}, 267 | {"/:id", true}, 268 | {"/*filepath", true}, 269 | } 270 | testRoutes(t, routes) 271 | } 272 | 273 | func TestTreeDupliatePath(t *testing.T) { 274 | tree := &node{} 275 | 276 | routes := [...]string{ 277 | "/", 278 | "/doc/", 279 | "/src/*filepath", 280 | "/search/:query", 281 | "/user_:name", 282 | } 283 | for _, route := range routes { 284 | recv := catchPanic(func() { 285 | tree.addRoute(route, fakeHandler(route)) 286 | }) 287 | if recv != nil { 288 | t.Fatalf("panic inserting route '%s': %v", route, recv) 289 | } 290 | 291 | // Add again 292 | recv = catchPanic(func() { 293 | tree.addRoute(route, nil) 294 | }) 295 | if recv == nil { 296 | t.Fatalf("no panic while inserting duplicate route '%s", route) 297 | } 298 | } 299 | 300 | //printChildren(tree, "") 301 | 302 | checkRequests(t, tree, testRequests{ 303 | {"/", false, "/", nil}, 304 | {"/doc/", false, "/doc/", nil}, 305 | {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, 306 | {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}}, 307 | {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, 308 | }) 309 | } 310 | 311 | func TestEmptyWildcardName(t *testing.T) { 312 | tree := &node{} 313 | 314 | routes := [...]string{ 315 | "/user:", 316 | "/user:/", 317 | "/cmd/:/", 318 | "/src/*", 319 | } 320 | for _, route := range routes { 321 | recv := catchPanic(func() { 322 | tree.addRoute(route, nil) 323 | }) 324 | if recv == nil { 325 | t.Fatalf("no panic while inserting route with empty wildcard name '%s", route) 326 | } 327 | } 328 | } 329 | 330 | func TestTreeCatchAllConflict(t *testing.T) { 331 | routes := []testRoute{ 332 | {"/src/*filepath/x", true}, 333 | {"/src2/", false}, 334 | {"/src2/*filepath/x", true}, 335 | } 336 | testRoutes(t, routes) 337 | } 338 | 339 | func TestTreeCatchAllConflictRoot(t *testing.T) { 340 | routes := []testRoute{ 341 | {"/", false}, 342 | {"/*filepath", true}, 343 | } 344 | testRoutes(t, routes) 345 | } 346 | 347 | func TestTreeDoubleWildcard(t *testing.T) { 348 | const panicMsg = "only one wildcard per path segment is allowed" 349 | 350 | routes := [...]string{ 351 | "/:foo:bar", 352 | "/:foo:bar/", 353 | "/:foo*bar", 354 | } 355 | 356 | for _, route := range routes { 357 | tree := &node{} 358 | recv := catchPanic(func() { 359 | tree.addRoute(route, nil) 360 | }) 361 | 362 | if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) { 363 | t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv) 364 | } 365 | } 366 | } 367 | 368 | /*func TestTreeDuplicateWildcard(t *testing.T) { 369 | tree := &node{} 370 | 371 | routes := [...]string{ 372 | "/:id/:name/:id", 373 | } 374 | for _, route := range routes { 375 | ... 376 | } 377 | }*/ 378 | 379 | func TestTreeTrailingSlashRedirect(t *testing.T) { 380 | tree := &node{} 381 | 382 | routes := [...]string{ 383 | "/hi", 384 | "/b/", 385 | "/search/:query", 386 | "/cmd/:tool/", 387 | "/src/*filepath", 388 | "/x", 389 | "/x/y", 390 | "/y/", 391 | "/y/z", 392 | "/0/:id", 393 | "/0/:id/1", 394 | "/1/:id/", 395 | "/1/:id/2", 396 | "/aa", 397 | "/a/", 398 | "/admin", 399 | "/admin/:category", 400 | "/admin/:category/:page", 401 | "/doc", 402 | "/doc/go_faq.html", 403 | "/doc/go1.html", 404 | "/no/a", 405 | "/no/b", 406 | "/api/hello/:name", 407 | } 408 | for _, route := range routes { 409 | recv := catchPanic(func() { 410 | tree.addRoute(route, fakeHandler(route)) 411 | }) 412 | if recv != nil { 413 | t.Fatalf("panic inserting route '%s': %v", route, recv) 414 | } 415 | } 416 | 417 | //printChildren(tree, "") 418 | 419 | tsrRoutes := [...]string{ 420 | "/hi/", 421 | "/b", 422 | "/search/gopher/", 423 | "/cmd/vet", 424 | "/src", 425 | "/x/", 426 | "/y", 427 | "/0/go/", 428 | "/1/go", 429 | "/a", 430 | "/admin/", 431 | "/admin/config/", 432 | "/admin/config/permissions/", 433 | "/doc/", 434 | } 435 | for _, route := range tsrRoutes { 436 | handler, _, tsr := tree.getValue(route) 437 | if handler != nil { 438 | t.Fatalf("non-nil handler for TSR route '%s", route) 439 | } else if !tsr { 440 | t.Errorf("expected TSR recommendation for route '%s'", route) 441 | } 442 | } 443 | 444 | noTsrRoutes := [...]string{ 445 | "/", 446 | "/no", 447 | "/no/", 448 | "/_", 449 | "/_/", 450 | "/api/world/abc", 451 | } 452 | for _, route := range noTsrRoutes { 453 | handler, _, tsr := tree.getValue(route) 454 | if handler != nil { 455 | t.Fatalf("non-nil handler for No-TSR route '%s", route) 456 | } else if tsr { 457 | t.Errorf("expected no TSR recommendation for route '%s'", route) 458 | } 459 | } 460 | } 461 | 462 | func TestTreeRootTrailingSlashRedirect(t *testing.T) { 463 | tree := &node{} 464 | 465 | recv := catchPanic(func() { 466 | tree.addRoute("/:test", fakeHandler("/:test")) 467 | }) 468 | if recv != nil { 469 | t.Fatalf("panic inserting test route: %v", recv) 470 | } 471 | 472 | handler, _, tsr := tree.getValue("/") 473 | if handler != nil { 474 | t.Fatalf("non-nil handler") 475 | } else if tsr { 476 | t.Errorf("expected no TSR recommendation") 477 | } 478 | } 479 | 480 | func TestTreeFindCaseInsensitivePath(t *testing.T) { 481 | tree := &node{} 482 | 483 | routes := [...]string{ 484 | "/hi", 485 | "/b/", 486 | "/ABC/", 487 | "/search/:query", 488 | "/cmd/:tool/", 489 | "/src/*filepath", 490 | "/x", 491 | "/x/y", 492 | "/y/", 493 | "/y/z", 494 | "/0/:id", 495 | "/0/:id/1", 496 | "/1/:id/", 497 | "/1/:id/2", 498 | "/aa", 499 | "/a/", 500 | "/doc", 501 | "/doc/go_faq.html", 502 | "/doc/go1.html", 503 | "/doc/go/away", 504 | "/no/a", 505 | "/no/b", 506 | "/Π", 507 | "/u/apfêl/", 508 | "/u/äpfêl/", 509 | "/u/öpfêl", 510 | "/v/Äpfêl/", 511 | "/v/Öpfêl", 512 | "/w/♬", // 3 byte 513 | "/w/♭/", // 3 byte, last byte differs 514 | "/w/𠜎", // 4 byte 515 | "/w/𠜏/", // 4 byte 516 | } 517 | 518 | for _, route := range routes { 519 | recv := catchPanic(func() { 520 | tree.addRoute(route, fakeHandler(route)) 521 | }) 522 | if recv != nil { 523 | t.Fatalf("panic inserting route '%s': %v", route, recv) 524 | } 525 | } 526 | 527 | // Check out == in for all registered routes 528 | // With fixTrailingSlash = true 529 | for _, route := range routes { 530 | out, found := tree.findCaseInsensitivePath(route, true) 531 | if !found { 532 | t.Errorf("Route '%s' not found!", route) 533 | } else if string(out) != route { 534 | t.Errorf("Wrong result for route '%s': %s", route, string(out)) 535 | } 536 | } 537 | // With fixTrailingSlash = false 538 | for _, route := range routes { 539 | out, found := tree.findCaseInsensitivePath(route, false) 540 | if !found { 541 | t.Errorf("Route '%s' not found!", route) 542 | } else if string(out) != route { 543 | t.Errorf("Wrong result for route '%s': %s", route, string(out)) 544 | } 545 | } 546 | 547 | tests := []struct { 548 | in string 549 | out string 550 | found bool 551 | slash bool 552 | }{ 553 | {"/HI", "/hi", true, false}, 554 | {"/HI/", "/hi", true, true}, 555 | {"/B", "/b/", true, true}, 556 | {"/B/", "/b/", true, false}, 557 | {"/abc", "/ABC/", true, true}, 558 | {"/abc/", "/ABC/", true, false}, 559 | {"/aBc", "/ABC/", true, true}, 560 | {"/aBc/", "/ABC/", true, false}, 561 | {"/abC", "/ABC/", true, true}, 562 | {"/abC/", "/ABC/", true, false}, 563 | {"/SEARCH/QUERY", "/search/QUERY", true, false}, 564 | {"/SEARCH/QUERY/", "/search/QUERY", true, true}, 565 | {"/CMD/TOOL/", "/cmd/TOOL/", true, false}, 566 | {"/CMD/TOOL", "/cmd/TOOL/", true, true}, 567 | {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false}, 568 | {"/x/Y", "/x/y", true, false}, 569 | {"/x/Y/", "/x/y", true, true}, 570 | {"/X/y", "/x/y", true, false}, 571 | {"/X/y/", "/x/y", true, true}, 572 | {"/X/Y", "/x/y", true, false}, 573 | {"/X/Y/", "/x/y", true, true}, 574 | {"/Y/", "/y/", true, false}, 575 | {"/Y", "/y/", true, true}, 576 | {"/Y/z", "/y/z", true, false}, 577 | {"/Y/z/", "/y/z", true, true}, 578 | {"/Y/Z", "/y/z", true, false}, 579 | {"/Y/Z/", "/y/z", true, true}, 580 | {"/y/Z", "/y/z", true, false}, 581 | {"/y/Z/", "/y/z", true, true}, 582 | {"/Aa", "/aa", true, false}, 583 | {"/Aa/", "/aa", true, true}, 584 | {"/AA", "/aa", true, false}, 585 | {"/AA/", "/aa", true, true}, 586 | {"/aA", "/aa", true, false}, 587 | {"/aA/", "/aa", true, true}, 588 | {"/A/", "/a/", true, false}, 589 | {"/A", "/a/", true, true}, 590 | {"/DOC", "/doc", true, false}, 591 | {"/DOC/", "/doc", true, true}, 592 | {"/NO", "", false, true}, 593 | {"/DOC/GO", "", false, true}, 594 | {"/π", "/Π", true, false}, 595 | {"/π/", "/Π", true, true}, 596 | {"/u/ÄPFÊL/", "/u/äpfêl/", true, false}, 597 | {"/u/ÄPFÊL", "/u/äpfêl/", true, true}, 598 | {"/u/ÖPFÊL/", "/u/öpfêl", true, true}, 599 | {"/u/ÖPFÊL", "/u/öpfêl", true, false}, 600 | {"/v/äpfêL/", "/v/Äpfêl/", true, false}, 601 | {"/v/äpfêL", "/v/Äpfêl/", true, true}, 602 | {"/v/öpfêL/", "/v/Öpfêl", true, true}, 603 | {"/v/öpfêL", "/v/Öpfêl", true, false}, 604 | {"/w/♬/", "/w/♬", true, true}, 605 | {"/w/♭", "/w/♭/", true, true}, 606 | {"/w/𠜎/", "/w/𠜎", true, true}, 607 | {"/w/𠜏", "/w/𠜏/", true, true}, 608 | } 609 | // With fixTrailingSlash = true 610 | for _, test := range tests { 611 | out, found := tree.findCaseInsensitivePath(test.in, true) 612 | if found != test.found || (found && (string(out) != test.out)) { 613 | t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", 614 | test.in, string(out), found, test.out, test.found) 615 | return 616 | } 617 | } 618 | // With fixTrailingSlash = false 619 | for _, test := range tests { 620 | out, found := tree.findCaseInsensitivePath(test.in, false) 621 | if test.slash { 622 | if found { // test needs a trailingSlash fix. It must not be found! 623 | t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out)) 624 | } 625 | } else { 626 | if found != test.found || (found && (string(out) != test.out)) { 627 | t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", 628 | test.in, string(out), found, test.out, test.found) 629 | return 630 | } 631 | } 632 | } 633 | } 634 | 635 | func TestTreeInvalidNodeType(t *testing.T) { 636 | const panicMsg = "invalid node type" 637 | 638 | tree := &node{} 639 | tree.addRoute("/", fakeHandler("/")) 640 | tree.addRoute("/:page", fakeHandler("/:page")) 641 | 642 | // set invalid node type 643 | tree.children[0].nType = 42 644 | 645 | // normal lookup 646 | recv := catchPanic(func() { 647 | tree.getValue("/test") 648 | }) 649 | if rs, ok := recv.(string); !ok || rs != panicMsg { 650 | t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) 651 | } 652 | 653 | // case-insensitive lookup 654 | recv = catchPanic(func() { 655 | tree.findCaseInsensitivePath("/test", true) 656 | }) 657 | if rs, ok := recv.(string); !ok || rs != panicMsg { 658 | t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) 659 | } 660 | } 661 | --------------------------------------------------------------------------------