1
0

router.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 httprouter
  77. import (
  78. "net/http"
  79. )
  80. // Handle is a function that can be registered to a route to handle HTTP
  81. // requests. Like http.HandlerFunc, but has a third parameter for the values of
  82. // wildcards (variables).
  83. type Handle func(http.ResponseWriter, *http.Request, Params)
  84. // Param is a single URL parameter, consisting of a key and a value.
  85. type Param struct {
  86. Key string
  87. Value string
  88. }
  89. // Params is a Param-slice, as returned by the router.
  90. // The slice is ordered, the first URL parameter is also the first slice value.
  91. // It is therefore safe to read values by the index.
  92. type Params []Param
  93. // ByName returns the value of the first Param which key matches the given name.
  94. // If no matching Param is found, an empty string is returned.
  95. func (ps Params) ByName(name string) string {
  96. for i := range ps {
  97. if ps[i].Key == name {
  98. return ps[i].Value
  99. }
  100. }
  101. return ""
  102. }
  103. // Router is a http.Handler which can be used to dispatch requests to different
  104. // handler functions via configurable routes
  105. type Router struct {
  106. trees map[string]*node
  107. // Enables automatic redirection if the current route can't be matched but a
  108. // handler for the path with (without) the trailing slash exists.
  109. // For example if /foo/ is requested but a route only exists for /foo, the
  110. // client is redirected to /foo with http status code 301 for GET requests
  111. // and 307 for all other request methods.
  112. RedirectTrailingSlash bool
  113. // If enabled, the router tries to fix the current request path, if no
  114. // handle is registered for it.
  115. // First superfluous path elements like ../ or // are removed.
  116. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  117. // If a handle can be found for this route, the router makes a redirection
  118. // to the corrected path with status code 301 for GET requests and 307 for
  119. // all other request methods.
  120. // For example /FOO and /..//Foo could be redirected to /foo.
  121. // RedirectTrailingSlash is independent of this option.
  122. RedirectFixedPath bool
  123. // If enabled, the router checks if another method is allowed for the
  124. // current route, if the current request can not be routed.
  125. // If this is the case, the request is answered with 'Method Not Allowed'
  126. // and HTTP status code 405.
  127. // If no other Method is allowed, the request is delegated to the NotFound
  128. // handler.
  129. HandleMethodNotAllowed bool
  130. // If enabled, the router automatically replies to OPTIONS requests.
  131. // Custom OPTIONS handlers take priority over automatic replies.
  132. HandleOPTIONS bool
  133. // Configurable http.Handler which is called when no matching route is
  134. // found. If it is not set, http.NotFound is used.
  135. NotFound http.Handler
  136. // Configurable http.Handler which is called when a request
  137. // cannot be routed and HandleMethodNotAllowed is true.
  138. // If it is not set, http.Error with http.StatusMethodNotAllowed is used.
  139. // The "Allow" header with allowed request methods is set before the handler
  140. // is called.
  141. MethodNotAllowed http.Handler
  142. // Function to handle panics recovered from http handlers.
  143. // It should be used to generate a error page and return the http error code
  144. // 500 (Internal Server Error).
  145. // The handler can be used to keep your server from crashing because of
  146. // unrecovered panics.
  147. PanicHandler func(http.ResponseWriter, *http.Request, interface{})
  148. }
  149. // Make sure the Router conforms with the http.Handler interface
  150. var _ http.Handler = New()
  151. // New returns a new initialized Router.
  152. // Path auto-correction, including trailing slashes, is enabled by default.
  153. func New() *Router {
  154. return &Router{
  155. RedirectTrailingSlash: true,
  156. RedirectFixedPath: true,
  157. HandleMethodNotAllowed: true,
  158. HandleOPTIONS: true,
  159. }
  160. }
  161. // GET is a shortcut for router.Handle("GET", path, handle)
  162. func (r *Router) GET(path string, handle Handle) {
  163. r.Handle("GET", path, handle)
  164. }
  165. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  166. func (r *Router) HEAD(path string, handle Handle) {
  167. r.Handle("HEAD", path, handle)
  168. }
  169. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  170. func (r *Router) OPTIONS(path string, handle Handle) {
  171. r.Handle("OPTIONS", path, handle)
  172. }
  173. // POST is a shortcut for router.Handle("POST", path, handle)
  174. func (r *Router) POST(path string, handle Handle) {
  175. r.Handle("POST", path, handle)
  176. }
  177. // PUT is a shortcut for router.Handle("PUT", path, handle)
  178. func (r *Router) PUT(path string, handle Handle) {
  179. r.Handle("PUT", path, handle)
  180. }
  181. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  182. func (r *Router) PATCH(path string, handle Handle) {
  183. r.Handle("PATCH", path, handle)
  184. }
  185. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  186. func (r *Router) DELETE(path string, handle Handle) {
  187. r.Handle("DELETE", path, handle)
  188. }
  189. // Handle registers a new request handle with the given path and method.
  190. //
  191. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  192. // functions can be used.
  193. //
  194. // This function is intended for bulk loading and to allow the usage of less
  195. // frequently used, non-standardized or custom methods (e.g. for internal
  196. // communication with a proxy).
  197. func (r *Router) Handle(method, path string, handle Handle) {
  198. if path[0] != '/' {
  199. panic("path must begin with '/' in path '" + path + "'")
  200. }
  201. if r.trees == nil {
  202. r.trees = make(map[string]*node)
  203. }
  204. root := r.trees[method]
  205. if root == nil {
  206. root = new(node)
  207. r.trees[method] = root
  208. }
  209. root.addRoute(path, handle)
  210. }
  211. // Handler is an adapter which allows the usage of an http.Handler as a
  212. // request handle.
  213. func (r *Router) Handler(method, path string, handler http.Handler) {
  214. r.Handle(method, path,
  215. func(w http.ResponseWriter, req *http.Request, _ Params) {
  216. handler.ServeHTTP(w, req)
  217. },
  218. )
  219. }
  220. // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
  221. // request handle.
  222. func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
  223. r.Handler(method, path, handler)
  224. }
  225. // ServeFiles serves files from the given file system root.
  226. // The path must end with "/*filepath", files are then served from the local
  227. // path /defined/root/dir/*filepath.
  228. // For example if root is "/etc" and *filepath is "passwd", the local file
  229. // "/etc/passwd" would be served.
  230. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  231. // of the Router's NotFound handler.
  232. // To use the operating system's file system implementation,
  233. // use http.Dir:
  234. // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
  235. func (r *Router) ServeFiles(path string, root http.FileSystem) {
  236. if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
  237. panic("path must end with /*filepath in path '" + path + "'")
  238. }
  239. fileServer := http.FileServer(root)
  240. r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
  241. req.URL.Path = ps.ByName("filepath")
  242. fileServer.ServeHTTP(w, req)
  243. })
  244. }
  245. func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
  246. if rcv := recover(); rcv != nil {
  247. r.PanicHandler(w, req, rcv)
  248. }
  249. }
  250. // Lookup allows the manual lookup of a method + path combo.
  251. // This is e.g. useful to build a framework around this router.
  252. // If the path was found, it returns the handle function and the path parameter
  253. // values. Otherwise the third return value indicates whether a redirection to
  254. // the same path with an extra / without the trailing slash should be performed.
  255. func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
  256. if root := r.trees[method]; root != nil {
  257. return root.getValue(path)
  258. }
  259. return nil, nil, false
  260. }
  261. func (r *Router) allowed(path, reqMethod string) (allow string) {
  262. if path == "*" { // server-wide
  263. for method := range r.trees {
  264. if method == "OPTIONS" {
  265. continue
  266. }
  267. // add request method to list of allowed methods
  268. if len(allow) == 0 {
  269. allow = method
  270. } else {
  271. allow += ", " + method
  272. }
  273. }
  274. } else { // specific path
  275. for method := range r.trees {
  276. // Skip the requested method - we already tried this one
  277. if method == reqMethod || method == "OPTIONS" {
  278. continue
  279. }
  280. handle, _, _ := r.trees[method].getValue(path)
  281. if handle != nil {
  282. // add request method to list of allowed methods
  283. if len(allow) == 0 {
  284. allow = method
  285. } else {
  286. allow += ", " + method
  287. }
  288. }
  289. }
  290. }
  291. if len(allow) > 0 {
  292. allow += ", OPTIONS"
  293. }
  294. return
  295. }
  296. // ServeHTTP makes the router implement the http.Handler interface.
  297. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  298. if r.PanicHandler != nil {
  299. defer r.recv(w, req)
  300. }
  301. path := req.URL.Path
  302. if root := r.trees[req.Method]; root != nil {
  303. if handle, ps, tsr := root.getValue(path); handle != nil {
  304. handle(w, req, ps)
  305. return
  306. } else if req.Method != "CONNECT" && path != "/" {
  307. code := 301 // Permanent redirect, request with GET method
  308. if req.Method != "GET" {
  309. // Temporary redirect, request with same method
  310. // As of Go 1.3, Go does not support status code 308.
  311. code = 307
  312. }
  313. if tsr && r.RedirectTrailingSlash {
  314. if len(path) > 1 && path[len(path)-1] == '/' {
  315. req.URL.Path = path[:len(path)-1]
  316. } else {
  317. req.URL.Path = path + "/"
  318. }
  319. http.Redirect(w, req, req.URL.String(), code)
  320. return
  321. }
  322. // Try to fix the request path
  323. if r.RedirectFixedPath {
  324. fixedPath, found := root.findCaseInsensitivePath(
  325. CleanPath(path),
  326. r.RedirectTrailingSlash,
  327. )
  328. if found {
  329. req.URL.Path = string(fixedPath)
  330. http.Redirect(w, req, req.URL.String(), code)
  331. return
  332. }
  333. }
  334. }
  335. }
  336. if req.Method == "OPTIONS" {
  337. // Handle OPTIONS requests
  338. if r.HandleOPTIONS {
  339. if allow := r.allowed(path, req.Method); len(allow) > 0 {
  340. w.Header().Set("Allow", allow)
  341. return
  342. }
  343. }
  344. } else {
  345. // Handle 405
  346. if r.HandleMethodNotAllowed {
  347. if allow := r.allowed(path, req.Method); len(allow) > 0 {
  348. w.Header().Set("Allow", allow)
  349. if r.MethodNotAllowed != nil {
  350. r.MethodNotAllowed.ServeHTTP(w, req)
  351. } else {
  352. http.Error(w,
  353. http.StatusText(http.StatusMethodNotAllowed),
  354. http.StatusMethodNotAllowed,
  355. )
  356. }
  357. return
  358. }
  359. }
  360. }
  361. // Handle 404
  362. if r.NotFound != nil {
  363. r.NotFound.ServeHTTP(w, req)
  364. } else {
  365. http.NotFound(w, req)
  366. }
  367. }