Aucune description

router.go 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. // Copyright 2018 Keelan Lightfoot. All rights reserved.
  2. // Copyright 2013 Julien Schmidt. All rights reserved.
  3. // Use of this source code is governed by a BSD-style license that can be found
  4. // in the LICENSE file.
  5. // Package pathrouter is a trie based high performance generic request router.
  6. //
  7. // A trivial example is:
  8. //
  9. // package main
  10. // import (
  11. // "fmt"
  12. // "github.com/naleek/pathrouter"
  13. // )
  14. //
  15. // func Hello(ps pathrouter.Params, d interface{}) {
  16. // u := d.(string)
  17. // fmt.Printf("hello, %s!\nUser Data: %s\n", ps.ByName("name"), u)
  18. // }
  19. //
  20. // func main() {
  21. // router := pathrouter.New()
  22. // router.Handle("/hello/:name", Hello)
  23. //
  24. // router.Execute("/hello/bob", "boring user data")
  25. // }
  26. //
  27. // The router matches incoming requests by the path.
  28. // If a handle is registered for this path and method, the router delegates the
  29. // request to that function.
  30. //
  31. // The registered path, against which the router matches incoming requests, can
  32. // contain two types of parameters:
  33. // Syntax Type
  34. // :name named parameter
  35. // *name catch-all parameter
  36. //
  37. // Named parameters are dynamic path segments. They match anything until the
  38. // next '/' or the path end:
  39. // Path: /blog/:category/:post
  40. //
  41. // Requests:
  42. // /blog/go/request-routers match: category="go", post="request-routers"
  43. // /blog/go/request-routers/ no match, but the router would redirect
  44. // /blog/go/ no match
  45. // /blog/go/request-routers/comments no match
  46. //
  47. // Catch-all parameters match anything until the path end, including the
  48. // directory index (the '/' before the catch-all). Since they match anything
  49. // until the end, catch-all parameters must always be the final path element.
  50. // Path: /files/*filepath
  51. //
  52. // Requests:
  53. // /files/ match: filepath="/"
  54. // /files/LICENSE match: filepath="/LICENSE"
  55. // /files/templates/article.html match: filepath="/templates/article.html"
  56. // /files no match, but the router would redirect
  57. //
  58. // The value of parameters is saved as a slice of the Param struct, consisting
  59. // each of a key and a value. The slice is passed to the Handle func as a third
  60. // parameter.
  61. // There are two ways to retrieve the value of a parameter:
  62. // // by the name of the parameter
  63. // user := ps.ByName("user") // defined by :user or *user
  64. //
  65. // // by the index of the parameter. This way you can also get the name (key)
  66. // thirdKey := ps[2].Key // the name of the 3rd parameter
  67. // thirdValue := ps[2].Value // the value of the 3rd parameter
  68. package pathrouter
  69. import (
  70. "errors"
  71. )
  72. var (
  73. // ErrRouteNotFound is reported when a matching route is not found
  74. ErrRouteNotFound = errors.New("pathrouter: no matching route found")
  75. )
  76. // Handle is a function that can be registered to a route to handle HTTP
  77. // requests. Like http.HandlerFunc, but has a third parameter for the values of
  78. // wildcards (variables).
  79. type Handle func(Params, interface{})
  80. // Param is a single URL parameter, consisting of a key and a value.
  81. type Param struct {
  82. Key string
  83. Value string
  84. }
  85. // Params is a Param-slice, as returned by the router.
  86. // The slice is ordered, the first URL parameter is also the first slice value.
  87. // It is therefore safe to read values by the index.
  88. type Params []Param
  89. // ByName returns the value of the first Param which key matches the given name.
  90. // If no matching Param is found, an empty string is returned.
  91. func (ps Params) ByName(name string) string {
  92. for i := range ps {
  93. if ps[i].Key == name {
  94. return ps[i].Value
  95. }
  96. }
  97. return ""
  98. }
  99. // Router is a http.Handler which can be used to dispatch requests to different
  100. // handler functions via configurable routes
  101. type Router struct {
  102. root *node
  103. }
  104. // New returns a new initialized Router.
  105. func New() *Router {
  106. return &Router{}
  107. }
  108. // Handle registers a new request handle with the given path.
  109. func (r *Router) Handle(path string, handle Handle) error {
  110. if path[0] != '/' {
  111. panic("path must begin with '/'")
  112. }
  113. if r.root == nil {
  114. r.root = new(node)
  115. }
  116. r.root.addRoute(path, handle)
  117. return nil
  118. }
  119. // Lookup allows the manual lookup of a method + path combo.
  120. // This is e.g. useful to build a framework around this router.
  121. // If the path was found, it returns the handle function and the path parameter
  122. // values.
  123. func (r *Router) Lookup(method, path string) (Handle, Params) {
  124. if root := r.root; root != nil {
  125. return root.getValue(path)
  126. }
  127. return nil, nil
  128. }
  129. // Execute runs the route if it exists
  130. func (r *Router) Execute(path string, userdata interface{}) error {
  131. if r.root != nil {
  132. if handle, ps := r.root.getValue(path); handle != nil {
  133. handle(ps, userdata)
  134. return nil
  135. }
  136. }
  137. return ErrRouteNotFound
  138. }