router.go 15 KB

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