router.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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) {
  18. // fmt.Fprint(w, "Welcome!\n")
  19. // }
  20. //
  21. // func Hello(w http.ResponseWriter, r *http.Request) {
  22. // var name string
  23. // if vars := httprouter.Vars(); vars != nil {
  24. // name, _ = vars["name"]
  25. // }
  26. // fmt.Fprintf(w, "hello, %s!\n", name)
  27. // }
  28. //
  29. // func main() {
  30. // router := httprouter.New()
  31. // router.GET("/", Index)
  32. // router.GET("/hello/:name", Hello)
  33. //
  34. // log.Fatal(http.ListenAndServe(":8080", router))
  35. // }
  36. //
  37. // The router matches incoming requests by the request method and the path.
  38. // If a handle is registered for this path and method, the router delegates the
  39. // request to that function.
  40. // For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
  41. // register handles, for all other methods router.Handle can be used.
  42. //
  43. // The registered path, against which the router matches incoming requests, can
  44. // contain two types of parameters:
  45. // Syntax Type
  46. // :name named parameter
  47. // *name catch-all parameter
  48. //
  49. // Named parameters are dynamic path segments. They match anything until the
  50. // next '/' or the path end:
  51. // Path: /blog/:category/:post
  52. //
  53. // Requests:
  54. // /blog/go/request-routers match: category="go", post="request-routers"
  55. // /blog/go/request-routers/ no match, but the router would redirect
  56. // /blog/go/ no match
  57. // /blog/go/request-routers/comments no match
  58. //
  59. // Catch-all parameters match anything until the path end, including the
  60. // directory index (the '/' before the catch-all). Since they match anything
  61. // until the end, catch-all parameters must always be the final path element.
  62. // Path: /files/*filepath
  63. //
  64. // Requests:
  65. // /files/ match: filepath="/"
  66. // /files/LICENSE match: filepath="/LICENSE"
  67. // /files/templates/article.html match: filepath="/templates/article.html"
  68. // /files no match, but the router would redirect
  69. //
  70. // The value of parameters is saved as a slice of the Param struct, consisting
  71. // each of a key and a value. The slice is passed to the Handle func as a third
  72. // parameter.
  73. // There are two ways to retrieve the value of a parameter:
  74. // // by the name of the parameter
  75. // user := ps.ByName("user") // defined by :user or *user
  76. //
  77. // // by the index of the parameter. This way you can also get the name (key)
  78. // thirdKey := ps[2].Key // the name of the 3rd parameter
  79. // thirdValue := ps[2].Value // the value of the 3rd parameter
  80. package httprouter
  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 = New()
  136. // New returns a new initialized Router.
  137. // Path auto-correction, including trailing slashes, is enabled by default.
  138. func New() *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("GET", 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("HEAD", 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("OPTIONS", 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("POST", 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("PUT", 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("PATCH", 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("DELETE", 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. // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
  197. // request handle.
  198. func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
  199. r.Handler(method, path, handler)
  200. }
  201. // ServeFiles serves files from the given file system root.
  202. // The path must end with "/*filepath", files are then served from the local
  203. // path /defined/root/dir/*filepath.
  204. // For example if root is "/etc" and *filepath is "passwd", the local file
  205. // "/etc/passwd" would be served.
  206. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  207. // of the Router's NotFound handler.
  208. // To use the operating system's file system implementation,
  209. // use http.Dir:
  210. // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
  211. func (r *Router) ServeFiles(path string, root http.FileSystem) {
  212. if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
  213. panic("path must end with /*filepath in path '" + path + "'")
  214. }
  215. fileServer := http.FileServer(root)
  216. r.GET(path, func(w http.ResponseWriter, req *http.Request) {
  217. if vars := Vars(req); vars != nil {
  218. path, _ := vars["filepath"]
  219. req.URL.Path = path
  220. }
  221. fileServer.ServeHTTP(w, req)
  222. })
  223. }
  224. func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
  225. if rcv := recover(); rcv != nil {
  226. r.PanicHandler(w, req, rcv)
  227. }
  228. }
  229. // Lookup allows the manual lookup of a method + path combo.
  230. // This is e.g. useful to build a framework around this router.
  231. // If the path was found, it returns the handle function and the path parameter
  232. // values. Otherwise the third return value indicates whether a redirection to
  233. // the same path with an extra / without the trailing slash should be performed.
  234. func (r *Router) Lookup(method, path string) (Handle, map[string]string, bool) {
  235. if root := r.trees[method]; root != nil {
  236. return root.getValue(path)
  237. }
  238. return nil, nil, false
  239. }
  240. func (r *Router) allowed(path, reqMethod string) (allow string) {
  241. if path == "*" { // server-wide
  242. for method := range r.trees {
  243. if method == "OPTIONS" {
  244. continue
  245. }
  246. // add request method to list of allowed methods
  247. if len(allow) == 0 {
  248. allow = method
  249. } else {
  250. allow += ", " + method
  251. }
  252. }
  253. } else { // specific path
  254. for method := range r.trees {
  255. // Skip the requested method - we already tried this one
  256. if method == reqMethod || method == "OPTIONS" {
  257. continue
  258. }
  259. handle, _, _ := r.trees[method].getValue(path)
  260. if handle != nil {
  261. // add request method to list of allowed methods
  262. if len(allow) == 0 {
  263. allow = method
  264. } else {
  265. allow += ", " + method
  266. }
  267. }
  268. }
  269. }
  270. if len(allow) > 0 {
  271. allow += ", OPTIONS"
  272. }
  273. return
  274. }
  275. // ServeHTTP makes the router implement the http.Handler interface.
  276. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  277. if r.PanicHandler != nil {
  278. defer r.recv(w, req)
  279. }
  280. path := req.URL.Path
  281. if root := r.trees[req.Method]; root != nil {
  282. if handle, ps, tsr := root.getValue(path); handle != nil {
  283. req = setVars(req, ps)
  284. req = setCurrentPath(req, path)
  285. handle(w, req)
  286. return
  287. } else if req.Method != "CONNECT" && path != "/" {
  288. code := 301 // Permanent redirect, request with GET method
  289. if req.Method != "GET" {
  290. // Temporary redirect, request with same method
  291. // As of Go 1.3, Go does not support status code 308.
  292. code = 307
  293. }
  294. if tsr && r.RedirectTrailingSlash {
  295. if len(path) > 1 && path[len(path)-1] == '/' {
  296. req.URL.Path = path[:len(path)-1]
  297. } else {
  298. req.URL.Path = path + "/"
  299. }
  300. http.Redirect(w, req, req.URL.String(), code)
  301. return
  302. }
  303. // Try to fix the request path
  304. if r.RedirectFixedPath {
  305. fixedPath, found := root.findCaseInsensitivePath(
  306. CleanPath(path),
  307. r.RedirectTrailingSlash,
  308. )
  309. if found {
  310. req.URL.Path = string(fixedPath)
  311. http.Redirect(w, req, req.URL.String(), code)
  312. return
  313. }
  314. }
  315. }
  316. }
  317. if req.Method == "OPTIONS" && r.HandleOPTIONS {
  318. // Handle OPTIONS requests
  319. if allow := r.allowed(path, req.Method); len(allow) > 0 {
  320. w.Header().Set("Allow", allow)
  321. return
  322. }
  323. } else {
  324. // Handle 405
  325. if r.HandleMethodNotAllowed {
  326. if allow := r.allowed(path, req.Method); len(allow) > 0 {
  327. w.Header().Set("Allow", allow)
  328. if r.MethodNotAllowed != nil {
  329. r.MethodNotAllowed.ServeHTTP(w, req)
  330. } else {
  331. http.Error(w,
  332. http.StatusText(http.StatusMethodNotAllowed),
  333. http.StatusMethodNotAllowed,
  334. )
  335. }
  336. return
  337. }
  338. }
  339. }
  340. // Handle 404
  341. if r.NotFound != nil {
  342. r.NotFound.ServeHTTP(w, req)
  343. } else {
  344. http.NotFound(w, req)
  345. }
  346. }