github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/http/httprouter/README.md (about) 1 # HttpRouter [](https://travis-ci.org/julienschmidt/httprouter) [](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [](http://pkg.go.dev/github.com/julienschmidt/httprouter) 2 3 HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/). 4 5 In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better. 6 7 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. 8 9 ## Features 10 11 **Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience. 12 13 **Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash). 14 15 **Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL. 16 17 **Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap. 18 19 **Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard `Handler`/`HandlerFunc` API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary. 20 21 **Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation. 22 23 **No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page. 24 25 **Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies. 26 27 Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles). 28 29 ## Usage 30 31 This is just a quick introduction, view the [Docs](http://pkg.go.dev/github.com/julienschmidt/httprouter) for details. 32 33 Let's start with a trivial example: 34 35 ```go 36 package main 37 38 import ( 39 "fmt" 40 "net/http" 41 "log" 42 43 "github.com/julienschmidt/httprouter" 44 ) 45 46 func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { 47 fmt.Fprint(w, "Welcome!\n") 48 } 49 50 func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 51 fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) 52 } 53 54 func main() { 55 router := httprouter.New() 56 router.GET("/", Index) 57 router.GET("/hello/:name", Hello) 58 59 log.Fatal(http.ListenAndServe(":8080", router)) 60 } 61 ``` 62 63 ### Named parameters 64 65 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 retrieved by `ByName("name")`. 66 67 When using a `http.Handler` (using `router.Handler` or `http.HandlerFunc`) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the `request.Context`. See more below under [Why doesn't this work with http.Handler?](#why-doesnt-this-work-with-httphandler). 68 69 Named parameters only match a single path segment: 70 71 ``` 72 Pattern: /user/:user 73 74 /user/gordon match 75 /user/you match 76 /user/gordon/profile no match 77 /user/ no match 78 ``` 79 80 **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. 81 82 ### Catch-All parameters 83 84 The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern: 85 86 ``` 87 Pattern: /src/*filepath 88 89 /src/ match 90 /src/somefile.go match 91 /src/subdir/somefile.go match 92 ``` 93 94 ## How does it work? 95 96 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: 97 98 ``` 99 Priority Path Handle 100 9 \ *<1> 101 3 ├s nil 102 2 |├earch\ *<2> 103 1 |└upport\ *<3> 104 2 ├blog\ *<4> 105 1 | └:post nil 106 1 | └\ *<5> 107 2 ├about-us\ *<6> 108 1 | └team\ *<7> 109 1 └contact\ *<8> 110 ``` 111 112 Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient. 113 114 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, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree. 115 116 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: 117 118 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. 119 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. 120 121 ``` 122 ├------------ 123 ├--------- 124 ├----- 125 ├---- 126 ├-- 127 ├-- 128 └- 129 ``` 130 131 ## Why doesn't this work with `http.Handler`? 132 133 **It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route. 134 135 Named parameters can be accessed `request.Context`: 136 137 ```go 138 func Hello(w http.ResponseWriter, r *http.Request) { 139 params := httprouter.ParamsFromContext(r.Context()) 140 141 fmt.Fprintf(w, "hello, %s!\n", params.ByName("name")) 142 } 143 ``` 144 145 Alternatively, one can also use `params := r.Context().Value(httprouter.ParamsKey)` instead of the helper function. 146 147 Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up. 148 149 ## Automatic OPTIONS responses and CORS 150 151 One might wish to modify automatic responses to OPTIONS requests, e.g. to support [CORS preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/preflight_request) or to set other headers. 152 This can be achieved using the [`Router.GlobalOPTIONS`](https://godoc.org/github.com/julienschmidt/httprouter#Router.GlobalOPTIONS) handler: 153 154 ```go 155 router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 156 if r.Header.Get("Access-Control-Request-Method") != "" { 157 // Set CORS headers 158 header := w.Header() 159 header.Set("Access-Control-Allow-Methods", header.Get("Allow")) 160 header.Set("Access-Control-Allow-Origin", "*") 161 } 162 163 // Adjust status code to 204 164 w.WriteHeader(http.StatusNoContent) 165 }) 166 ``` 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`](https://golang.org/pkg/net/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 http.Handler interface. 182 // Therefore we need a type for which we implement the ServeHTTP method. 183 // We just use a map here, in which we map host names (with port) to http.Handlers 184 type HostSwitch map[string]http.Handler 185 186 // Implement the ServeHTTP method on our new type 187 func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) { 188 // Check if a http.Handler is registered for the given host. 189 // If yes, use it to handle the request. 190 if handler := hs[r.Host]; handler != nil { 191 handler.ServeHTTP(w, r) 192 } else { 193 // Handle host names for which no handler is registered 194 http.Error(w, "Forbidden", 403) // Or Redirect? 195 } 196 } 197 198 func main() { 199 // Initialize a router as usual 200 router := httprouter.New() 201 router.GET("/", Index) 202 router.GET("/hello/:name", Hello) 203 204 // Make a new HostSwitch and insert the router (our http handler) 205 // for example.com and port 12345 206 hs := make(HostSwitch) 207 hs["example.com:12345"] = router 208 209 // Use the HostSwitch to listen and serve on port 12345 210 log.Fatal(http.ListenAndServe(":12345", hs)) 211 } 212 ``` 213 214 ### Basic Authentication 215 216 Another quick example: Basic Authentication (RFC 2617) for handles: 217 218 ```go 219 package main 220 221 import ( 222 "fmt" 223 "log" 224 "net/http" 225 226 "github.com/julienschmidt/httprouter" 227 ) 228 229 func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle { 230 return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { 231 // Get the Basic Authentication credentials 232 user, password, hasAuth := r.BasicAuth() 233 234 if hasAuth && user == requiredUser && password == requiredPassword { 235 // Delegate request to the given handle 236 h(w, r, ps) 237 } else { 238 // Request Basic Authentication otherwise 239 w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") 240 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) 241 } 242 } 243 } 244 245 func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { 246 fmt.Fprint(w, "Not protected!\n") 247 } 248 249 func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { 250 fmt.Fprint(w, "Protected!\n") 251 } 252 253 func main() { 254 user := "gordon" 255 pass := "secret!" 256 257 router := httprouter.New() 258 router.GET("/", Index) 259 router.GET("/protected/", BasicAuth(Protected, user, pass)) 260 261 log.Fatal(http.ListenAndServe(":8080", router)) 262 } 263 ``` 264 265 ## Chaining with the NotFound handler 266 267 **NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.** 268 269 You can use another [`http.Handler`](https://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`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining. 270 271 ### Static files 272 273 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): 274 275 ```go 276 // Serve static files from the ./public directory 277 router.NotFound = http.FileServer(http.Dir("public")) 278 ``` 279 280 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`. 281 282 ## Web Frameworks based on HttpRouter 283 284 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: 285 286 * [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework 287 * [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go 288 * [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance 289 * [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go 290 * [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain 291 * [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine 292 * [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow 293 * [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support 294 * [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context 295 * [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba 296 * [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang 297 * [pbgo](https://github.com/chai2010/pbgo): pbgo is a mini RPC/REST framework based on Protobuf 298 * [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server 299 * [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts 300 * [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware)