router.go 13 KB

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