router.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // Package httprouter is a trie based high performance HTTP request router.
  5. //
  6. // A trivial example is:
  7. //
  8. // package main
  9. //
  10. // import (
  11. // "fmt"
  12. // "github.com/julienschmidt/httprouter"
  13. // "net/http"
  14. // "log"
  15. // )
  16. //
  17. // func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  18. // fmt.Fprint(w, "Welcome!\n")
  19. // }
  20. //
  21. // func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  22. // fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
  23. // }
  24. //
  25. // func main() {
  26. // router := httprouter.New()
  27. // router.GET("/", Index)
  28. // router.GET("/hello/:name", Hello)
  29. //
  30. // log.Fatal(http.ListenAndServe(":8080", router))
  31. // }
  32. //
  33. // The router matches incoming requests by the request method and the path.
  34. // If a handle is registered for this path and method, the router delegates the
  35. // request to that function.
  36. // For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
  37. // register handles, for all other methods router.Handle can be used.
  38. //
  39. // The registered path, against which the router matches incoming requests, can
  40. // contain two types of parameters:
  41. // Syntax Type
  42. // :name named parameter
  43. // *name catch-all parameter
  44. //
  45. // Named parameters are dynamic path segments. They match anything until the
  46. // next '/' or the path end:
  47. // Path: /blog/:category/:post
  48. //
  49. // Requests:
  50. // /blog/go/request-routers match: category="go", post="request-routers"
  51. // /blog/go/request-routers/ no match, but the router would redirect
  52. // /blog/go/ no match
  53. // /blog/go/request-routers/comments no match
  54. //
  55. // Catch-all parameters match anything until the path end, including the
  56. // directory index (the '/' before the catch-all). Since they match anything
  57. // until the end, catch-all parameters must always be the final path element.
  58. // Path: /files/*filepath
  59. //
  60. // Requests:
  61. // /files/ match: filepath="/"
  62. // /files/LICENSE match: filepath="/LICENSE"
  63. // /files/templates/article.html match: filepath="/templates/article.html"
  64. // /files no match, but the router would redirect
  65. //
  66. // The value of parameters is saved as a slice of the Param struct, consisting
  67. // each of a key and a value. The slice is passed to the Handle func as a third
  68. // parameter.
  69. // There are two ways to retrieve the value of a parameter:
  70. // // by the name of the parameter
  71. // user := ps.ByName("user") // defined by :user or *user
  72. //
  73. // // by the index of the parameter. This way you can also get the name (key)
  74. // thirdKey := ps[2].Key // the name of the 3rd parameter
  75. // thirdValue := ps[2].Value // the value of the 3rd parameter
  76. package router
  77. import (
  78. "context"
  79. "net/http"
  80. "strings"
  81. )
  82. // Handle is a function that can be registered to a route to handle HTTP
  83. // requests. Like http.HandlerFunc, but has a third parameter for the values of
  84. // wildcards (variables).
  85. type Handle func(http.ResponseWriter, *http.Request, Params)
  86. // Param is a single URL parameter, consisting of a key and a value.
  87. type Param struct {
  88. Key string
  89. Value string
  90. }
  91. // Params is a Param-slice, as returned by the router.
  92. // The slice is ordered, the first URL parameter is also the first slice value.
  93. // It is therefore safe to read values by the index.
  94. type Params []Param
  95. // ByName returns the value of the first Param which key matches the given name.
  96. // If no matching Param is found, an empty string is returned.
  97. func (ps Params) ByName(name string) string {
  98. for i := range ps {
  99. if ps[i].Key == name {
  100. return ps[i].Value
  101. }
  102. }
  103. return ""
  104. }
  105. type paramsKey struct{}
  106. // ParamsKey is the request context key under which URL params are stored.
  107. var ParamsKey = paramsKey{}
  108. // ParamsFromContext pulls the URL parameters from a request context,
  109. // or returns nil if none are present.
  110. func ParamsFromContext(ctx context.Context) Params {
  111. p, _ := ctx.Value(ParamsKey).(Params)
  112. return p
  113. }
  114. // Router is a http.Handler which can be used to dispatch requests to different
  115. // handler functions via configurable routes
  116. type Router struct {
  117. trees map[string]*node
  118. // Enables automatic redirection if the current route can't be matched but a
  119. // handler for the path with (without) the trailing slash exists.
  120. // For example if /foo/ is requested but a route only exists for /foo, the
  121. // client is redirected to /foo with http status code 301 for GET requests
  122. // and 307 for all other request methods.
  123. RedirectTrailingSlash bool
  124. // If enabled, the router tries to fix the current request path, if no
  125. // handle is registered for it.
  126. // First superfluous path elements like ../ or // are removed.
  127. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  128. // If a handle can be found for this route, the router makes a redirection
  129. // to the corrected path with status code 301 for GET requests and 307 for
  130. // all other request methods.
  131. // For example /FOO and /..//Foo could be redirected to /foo.
  132. // RedirectTrailingSlash is independent of this option.
  133. RedirectFixedPath bool
  134. // If enabled, the router checks if another method is allowed for the
  135. // current route, if the current request can not be routed.
  136. // If this is the case, the request is answered with 'Method Not Allowed'
  137. // and HTTP status code 405.
  138. // If no other Method is allowed, the request is delegated to the NotFound
  139. // handler.
  140. HandleMethodNotAllowed bool
  141. // If enabled, the router automatically replies to OPTIONS requests.
  142. // Custom OPTIONS handlers take priority over automatic replies.
  143. HandleOPTIONS bool
  144. // An optional http.Handler that is called on automatic OPTIONS requests.
  145. // The handler is only called if HandleOPTIONS is true and no OPTIONS
  146. // handler for the specific path was set.
  147. // The "Allowed" header is set before calling the handler.
  148. GlobalOPTIONS http.Handler
  149. // Cached value of global (*) allowed methods
  150. globalAllowed string
  151. // Configurable http.Handler which is called when no matching route is
  152. // found. If it is not set, http.NotFound is used.
  153. NotFound http.Handler
  154. // Configurable http.Handler which is called when a request
  155. // cannot be routed and HandleMethodNotAllowed is true.
  156. // If it is not set, http.Error with http.StatusMethodNotAllowed is used.
  157. // The "Allow" header with allowed request methods is set before the handler
  158. // is called.
  159. MethodNotAllowed http.Handler
  160. // Function to handle panics recovered from http handlers.
  161. // It should be used to generate a error page and return the http error code
  162. // 500 (Internal Server Error).
  163. // The handler can be used to keep your server from crashing because of
  164. // unrecovered panics.
  165. PanicHandler func(http.ResponseWriter, *http.Request, interface{})
  166. }
  167. // Make sure the Router conforms with the http.Handler interface
  168. var _ http.Handler = New()
  169. // New returns a new initialized Router.
  170. // Path auto-correction, including trailing slashes, is enabled by default.
  171. func New() *Router {
  172. return &Router{
  173. RedirectTrailingSlash: true,
  174. RedirectFixedPath: true,
  175. HandleMethodNotAllowed: true,
  176. HandleOPTIONS: true,
  177. }
  178. }
  179. // GET is a shortcut for router.Handle(http.MethodGet, path, handle)
  180. func (r *Router) GET(path string, handle Handle) {
  181. r.Handle(http.MethodGet, path, handle)
  182. }
  183. // HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)
  184. func (r *Router) HEAD(path string, handle Handle) {
  185. r.Handle(http.MethodHead, path, handle)
  186. }
  187. // OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)
  188. func (r *Router) OPTIONS(path string, handle Handle) {
  189. r.Handle(http.MethodOptions, path, handle)
  190. }
  191. // POST is a shortcut for router.Handle(http.MethodPost, path, handle)
  192. func (r *Router) POST(path string, handle Handle) {
  193. r.Handle(http.MethodPost, path, handle)
  194. }
  195. // PUT is a shortcut for router.Handle(http.MethodPut, path, handle)
  196. func (r *Router) PUT(path string, handle Handle) {
  197. r.Handle(http.MethodPut, path, handle)
  198. }
  199. // PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)
  200. func (r *Router) PATCH(path string, handle Handle) {
  201. r.Handle(http.MethodPatch, path, handle)
  202. }
  203. // DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)
  204. func (r *Router) DELETE(path string, handle Handle) {
  205. r.Handle(http.MethodDelete, path, handle)
  206. }
  207. // Handle registers a new request handle with the given path and method.
  208. //
  209. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  210. // functions can be used.
  211. //
  212. // This function is intended for bulk loading and to allow the usage of less
  213. // frequently used, non-standardized or custom methods (e.g. for internal
  214. // communication with a proxy).
  215. func (r *Router) Handle(method, path string, handle Handle) {
  216. if len(path) < 1 || path[0] != '/' {
  217. panic("path must begin with '/' in path '" + path + "'")
  218. }
  219. if r.trees == nil {
  220. r.trees = make(map[string]*node)
  221. }
  222. root := r.trees[method]
  223. if root == nil {
  224. root = new(node)
  225. r.trees[method] = root
  226. r.globalAllowed = r.allowed("*", "")
  227. }
  228. root.addRoute(path, handle)
  229. }
  230. // Handler is an adapter which allows the usage of an http.Handler as a
  231. // request handle.
  232. // The Params are available in the request context under ParamsKey.
  233. func (r *Router) Handler(method, path string, handler http.Handler) {
  234. r.Handle(method, path,
  235. func(w http.ResponseWriter, req *http.Request, p Params) {
  236. if len(p) > 0 {
  237. ctx := req.Context()
  238. ctx = context.WithValue(ctx, ParamsKey, p)
  239. req = req.WithContext(ctx)
  240. }
  241. handler.ServeHTTP(w, req)
  242. },
  243. )
  244. }
  245. // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
  246. // request handle.
  247. func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
  248. r.Handler(method, path, handler)
  249. }
  250. // ServeFiles serves files from the given file system root.
  251. // The path must end with "/*filepath", files are then served from the local
  252. // path /defined/root/dir/*filepath.
  253. // For example if root is "/etc" and *filepath is "passwd", the local file
  254. // "/etc/passwd" would be served.
  255. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  256. // of the Router's NotFound handler.
  257. // To use the operating system's file system implementation,
  258. // use http.Dir:
  259. // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
  260. func (r *Router) ServeFiles(path string, root http.FileSystem) {
  261. if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
  262. panic("path must end with /*filepath in path '" + path + "'")
  263. }
  264. fileServer := http.FileServer(root)
  265. r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
  266. req.URL.Path = ps.ByName("filepath")
  267. fileServer.ServeHTTP(w, req)
  268. })
  269. }
  270. func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
  271. if rcv := recover(); rcv != nil {
  272. r.PanicHandler(w, req, rcv)
  273. }
  274. }
  275. // Lookup allows the manual lookup of a method + path combo.
  276. // This is e.g. useful to build a framework around this router.
  277. // If the path was found, it returns the handle function and the path parameter
  278. // values. Otherwise the third return value indicates whether a redirection to
  279. // the same path with an extra / without the trailing slash should be performed.
  280. func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
  281. if root := r.trees[method]; root != nil {
  282. return root.getValue(path)
  283. }
  284. return nil, nil, false
  285. }
  286. func (r *Router) allowed(path, reqMethod string) (allow string) {
  287. allowed := make([]string, 0, 9)
  288. if path == "*" { // server-wide
  289. // empty method is used for internal calls to refresh the cache
  290. if reqMethod == "" {
  291. for method := range r.trees {
  292. if method == http.MethodOptions {
  293. continue
  294. }
  295. // Add request method to list of allowed methods
  296. allowed = append(allowed, method)
  297. }
  298. } else {
  299. return r.globalAllowed
  300. }
  301. } else { // specific path
  302. for method := range r.trees {
  303. // Skip the requested method - we already tried this one
  304. if method == reqMethod || method == http.MethodOptions {
  305. continue
  306. }
  307. handle, _, _ := r.trees[method].getValue(path)
  308. if handle != nil {
  309. // Add request method to list of allowed methods
  310. allowed = append(allowed, method)
  311. }
  312. }
  313. }
  314. if len(allowed) > 0 {
  315. // Add request method to list of allowed methods
  316. allowed = append(allowed, http.MethodOptions)
  317. // Sort allowed methods.
  318. // sort.Strings(allowed) unfortunately causes unnecessary allocations
  319. // due to allowed being moved to the heap and interface conversion
  320. for i, l := 1, len(allowed); i < l; i++ {
  321. for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
  322. allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
  323. }
  324. }
  325. // return as comma separated list
  326. return strings.Join(allowed, ", ")
  327. }
  328. return
  329. }
  330. // ServeHTTP makes the router implement the http.Handler interface.
  331. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  332. if r.PanicHandler != nil {
  333. defer r.recv(w, req)
  334. }
  335. path := req.URL.Path
  336. if root := r.trees[req.Method]; root != nil {
  337. if handle, ps, tsr := root.getValue(path); handle != nil {
  338. handle(w, req, ps)
  339. return
  340. } else if req.Method != http.MethodConnect && path != "/" {
  341. code := 301 // Permanent redirect, request with GET method
  342. if req.Method != http.MethodGet {
  343. // Temporary redirect, request with same method
  344. // As of Go 1.3, Go does not support status code 308.
  345. code = 307
  346. }
  347. if tsr && r.RedirectTrailingSlash {
  348. if len(path) > 1 && path[len(path)-1] == '/' {
  349. req.URL.Path = path[:len(path)-1]
  350. } else {
  351. req.URL.Path = path + "/"
  352. }
  353. http.Redirect(w, req, req.URL.String(), code)
  354. return
  355. }
  356. // Try to fix the request path
  357. if r.RedirectFixedPath {
  358. fixedPath, found := root.findCaseInsensitivePath(
  359. CleanPath(path),
  360. r.RedirectTrailingSlash,
  361. )
  362. if found {
  363. req.URL.Path = string(fixedPath)
  364. http.Redirect(w, req, req.URL.String(), code)
  365. return
  366. }
  367. }
  368. }
  369. }
  370. if req.Method == http.MethodOptions && r.HandleOPTIONS {
  371. // Handle OPTIONS requests
  372. if allow := r.allowed(path, http.MethodOptions); allow != "" {
  373. w.Header().Set("Allow", allow)
  374. if r.GlobalOPTIONS != nil {
  375. r.GlobalOPTIONS.ServeHTTP(w, req)
  376. }
  377. return
  378. }
  379. } else if r.HandleMethodNotAllowed { // Handle 405
  380. if allow := r.allowed(path, req.Method); allow != "" {
  381. w.Header().Set("Allow", allow)
  382. if r.MethodNotAllowed != nil {
  383. r.MethodNotAllowed.ServeHTTP(w, req)
  384. } else {
  385. http.Error(w,
  386. http.StatusText(http.StatusMethodNotAllowed),
  387. http.StatusMethodNotAllowed,
  388. )
  389. }
  390. return
  391. }
  392. }
  393. // Handle 404
  394. if r.NotFound != nil {
  395. r.NotFound.ServeHTTP(w, req)
  396. } else {
  397. http.NotFound(w, req)
  398. }
  399. }