1
0

router.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 paramerters 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. // Configurable http.HandlerFunc which is called when no matching route is
  131. // found. If it is not set, http.NotFound is used.
  132. NotFound http.HandlerFunc
  133. // Configurable http.HandlerFunc which is called when a request
  134. // cannot be routed and HandleMethodNotAllowed is true.
  135. // If it is not set, http.Error with http.StatusMethodNotAllowed is used.
  136. MethodNotAllowed http.HandlerFunc
  137. // Function to handle panics recovered from http handlers.
  138. // It should be used to generate a error page and return the http error code
  139. // 500 (Internal Server Error).
  140. // The handler can be used to keep your server from crashing because of
  141. // unrecovered panics.
  142. PanicHandler func(http.ResponseWriter, *http.Request, interface{})
  143. }
  144. // Make sure the Router conforms with the http.Handler interface
  145. var _ http.Handler = New()
  146. // New returns a new initialized Router.
  147. // Path auto-correction, including trailing slashes, is enabled by default.
  148. func New() *Router {
  149. return &Router{
  150. RedirectTrailingSlash: true,
  151. RedirectFixedPath: true,
  152. HandleMethodNotAllowed: true,
  153. }
  154. }
  155. // GET is a shortcut for router.Handle("GET", path, handle)
  156. func (r *Router) GET(path string, handle Handle) {
  157. r.Handle("GET", path, handle)
  158. }
  159. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  160. func (r *Router) HEAD(path string, handle Handle) {
  161. r.Handle("HEAD", path, handle)
  162. }
  163. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  164. func (r *Router) OPTIONS(path string, handle Handle) {
  165. r.Handle("OPTIONS", path, handle)
  166. }
  167. // POST is a shortcut for router.Handle("POST", path, handle)
  168. func (r *Router) POST(path string, handle Handle) {
  169. r.Handle("POST", path, handle)
  170. }
  171. // PUT is a shortcut for router.Handle("PUT", path, handle)
  172. func (r *Router) PUT(path string, handle Handle) {
  173. r.Handle("PUT", path, handle)
  174. }
  175. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  176. func (r *Router) PATCH(path string, handle Handle) {
  177. r.Handle("PATCH", path, handle)
  178. }
  179. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  180. func (r *Router) DELETE(path string, handle Handle) {
  181. r.Handle("DELETE", path, handle)
  182. }
  183. // Handle registers a new request handle with the given path and method.
  184. //
  185. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  186. // functions can be used.
  187. //
  188. // This function is intended for bulk loading and to allow the usage of less
  189. // frequently used, non-standardized or custom methods (e.g. for internal
  190. // communication with a proxy).
  191. func (r *Router) Handle(method, path string, handle Handle) {
  192. if path[0] != '/' {
  193. panic("path must begin with '/' in path '" + path + "'")
  194. }
  195. if r.trees == nil {
  196. r.trees = make(map[string]*node)
  197. }
  198. root := r.trees[method]
  199. if root == nil {
  200. root = new(node)
  201. r.trees[method] = root
  202. }
  203. root.addRoute(path, handle)
  204. }
  205. // Handler is an adapter which allows the usage of an http.Handler as a
  206. // request handle.
  207. func (r *Router) Handler(method, path string, handler http.Handler) {
  208. r.Handle(method, path,
  209. func(w http.ResponseWriter, req *http.Request, _ Params) {
  210. handler.ServeHTTP(w, req)
  211. },
  212. )
  213. }
  214. // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
  215. // request handle.
  216. func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
  217. r.Handler(method, path, handler)
  218. }
  219. // ServeFiles serves files from the given file system root.
  220. // The path must end with "/*filepath", files are then served from the local
  221. // path /defined/root/dir/*filepath.
  222. // For example if root is "/etc" and *filepath is "passwd", the local file
  223. // "/etc/passwd" would be served.
  224. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  225. // of the Router's NotFound handler.
  226. // To use the operating system's file system implementation,
  227. // use http.Dir:
  228. // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
  229. func (r *Router) ServeFiles(path string, root http.FileSystem) {
  230. if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
  231. panic("path must end with /*filepath in path '" + path + "'")
  232. }
  233. fileServer := http.FileServer(root)
  234. r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
  235. req.URL.Path = ps.ByName("filepath")
  236. fileServer.ServeHTTP(w, req)
  237. })
  238. }
  239. func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
  240. if rcv := recover(); rcv != nil {
  241. r.PanicHandler(w, req, rcv)
  242. }
  243. }
  244. // Lookup allows the manual lookup of a method + path combo.
  245. // This is e.g. useful to build a framework around this router.
  246. // If the path was found, it returns the handle function and the path parameter
  247. // values. Otherwise the third return value indicates whether a redirection to
  248. // the same path with an extra / without the trailing slash should be performed.
  249. func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
  250. if root := r.trees[method]; root != nil {
  251. return root.getValue(path)
  252. }
  253. return nil, nil, false
  254. }
  255. // ServeHTTP makes the router implement the http.Handler interface.
  256. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  257. if r.PanicHandler != nil {
  258. defer r.recv(w, req)
  259. }
  260. if root := r.trees[req.Method]; root != nil {
  261. path := req.URL.Path
  262. if handle, ps, tsr := root.getValue(path); handle != nil {
  263. handle(w, req, ps)
  264. return
  265. } else if req.Method != "CONNECT" && path != "/" {
  266. code := 301 // Permanent redirect, request with GET method
  267. if req.Method != "GET" {
  268. // Temporary redirect, request with same method
  269. // As of Go 1.3, Go does not support status code 308.
  270. code = 307
  271. }
  272. if tsr && r.RedirectTrailingSlash {
  273. if len(path) > 1 && path[len(path)-1] == '/' {
  274. req.URL.Path = path[:len(path)-1]
  275. } else {
  276. req.URL.Path = path + "/"
  277. }
  278. http.Redirect(w, req, req.URL.String(), code)
  279. return
  280. }
  281. // Try to fix the request path
  282. if r.RedirectFixedPath {
  283. fixedPath, found := root.findCaseInsensitivePath(
  284. CleanPath(path),
  285. r.RedirectTrailingSlash,
  286. )
  287. if found {
  288. req.URL.Path = string(fixedPath)
  289. http.Redirect(w, req, req.URL.String(), code)
  290. return
  291. }
  292. }
  293. }
  294. }
  295. // Handle 405
  296. if r.HandleMethodNotAllowed {
  297. for method := range r.trees {
  298. // Skip the requested method - we already tried this one
  299. if method == req.Method {
  300. continue
  301. }
  302. handle, _, _ := r.trees[method].getValue(req.URL.Path)
  303. if handle != nil {
  304. if r.MethodNotAllowed != nil {
  305. r.MethodNotAllowed(w, req)
  306. } else {
  307. http.Error(w,
  308. http.StatusText(http.StatusMethodNotAllowed),
  309. http.StatusMethodNotAllowed,
  310. )
  311. }
  312. return
  313. }
  314. }
  315. }
  316. // Handle 404
  317. if r.NotFound != nil {
  318. r.NotFound(w, req)
  319. } else {
  320. http.NotFound(w, req)
  321. }
  322. }