Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

router.go 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2014 The Macaron Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package macaron
  15. import (
  16. "net/http"
  17. "strings"
  18. "sync"
  19. )
  20. var (
  21. // Known HTTP methods.
  22. _HTTP_METHODS = map[string]bool{
  23. "GET": true,
  24. "POST": true,
  25. "PUT": true,
  26. "DELETE": true,
  27. "PATCH": true,
  28. "OPTIONS": true,
  29. "HEAD": true,
  30. }
  31. )
  32. // routeMap represents a thread-safe map for route tree.
  33. type routeMap struct {
  34. lock sync.RWMutex
  35. routes map[string]map[string]*Leaf
  36. }
  37. // NewRouteMap initializes and returns a new routeMap.
  38. func NewRouteMap() *routeMap {
  39. rm := &routeMap{
  40. routes: make(map[string]map[string]*Leaf),
  41. }
  42. for m := range _HTTP_METHODS {
  43. rm.routes[m] = make(map[string]*Leaf)
  44. }
  45. return rm
  46. }
  47. // getLeaf returns Leaf object if a route has been registered.
  48. func (rm *routeMap) getLeaf(method, pattern string) *Leaf {
  49. rm.lock.RLock()
  50. defer rm.lock.RUnlock()
  51. return rm.routes[method][pattern]
  52. }
  53. // add adds new route to route tree map.
  54. func (rm *routeMap) add(method, pattern string, leaf *Leaf) {
  55. rm.lock.Lock()
  56. defer rm.lock.Unlock()
  57. rm.routes[method][pattern] = leaf
  58. }
  59. type group struct {
  60. pattern string
  61. handlers []Handler
  62. }
  63. // Router represents a Macaron router layer.
  64. type Router struct {
  65. m *Macaron
  66. autoHead bool
  67. routers map[string]*Tree
  68. *routeMap
  69. namedRoutes map[string]*Leaf
  70. groups []group
  71. notFound http.HandlerFunc
  72. internalServerError func(*Context, error)
  73. }
  74. func NewRouter() *Router {
  75. return &Router{
  76. routers: make(map[string]*Tree),
  77. routeMap: NewRouteMap(),
  78. namedRoutes: make(map[string]*Leaf),
  79. }
  80. }
  81. // SetAutoHead sets the value who determines whether add HEAD method automatically
  82. // when GET method is added. Combo router will not be affected by this value.
  83. func (r *Router) SetAutoHead(v bool) {
  84. r.autoHead = v
  85. }
  86. type Params map[string]string
  87. // Handle is a function that can be registered to a route to handle HTTP requests.
  88. // Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
  89. type Handle func(http.ResponseWriter, *http.Request, Params)
  90. // Route represents a wrapper of leaf route and upper level router.
  91. type Route struct {
  92. router *Router
  93. leaf *Leaf
  94. }
  95. // Name sets name of route.
  96. func (r *Route) Name(name string) {
  97. if len(name) == 0 {
  98. panic("route name cannot be empty")
  99. } else if r.router.namedRoutes[name] != nil {
  100. panic("route with given name already exists")
  101. }
  102. r.router.namedRoutes[name] = r.leaf
  103. }
  104. // handle adds new route to the router tree.
  105. func (r *Router) handle(method, pattern string, handle Handle) *Route {
  106. method = strings.ToUpper(method)
  107. var leaf *Leaf
  108. // Prevent duplicate routes.
  109. if leaf = r.getLeaf(method, pattern); leaf != nil {
  110. return &Route{r, leaf}
  111. }
  112. // Validate HTTP methods.
  113. if !_HTTP_METHODS[method] && method != "*" {
  114. panic("unknown HTTP method: " + method)
  115. }
  116. // Generate methods need register.
  117. methods := make(map[string]bool)
  118. if method == "*" {
  119. for m := range _HTTP_METHODS {
  120. methods[m] = true
  121. }
  122. } else {
  123. methods[method] = true
  124. }
  125. // Add to router tree.
  126. for m := range methods {
  127. if t, ok := r.routers[m]; ok {
  128. leaf = t.Add(pattern, handle)
  129. } else {
  130. t := NewTree()
  131. leaf = t.Add(pattern, handle)
  132. r.routers[m] = t
  133. }
  134. r.add(m, pattern, leaf)
  135. }
  136. return &Route{r, leaf}
  137. }
  138. // Handle registers a new request handle with the given pattern, method and handlers.
  139. func (r *Router) Handle(method string, pattern string, handlers []Handler) *Route {
  140. if len(r.groups) > 0 {
  141. groupPattern := ""
  142. h := make([]Handler, 0)
  143. for _, g := range r.groups {
  144. groupPattern += g.pattern
  145. h = append(h, g.handlers...)
  146. }
  147. pattern = groupPattern + pattern
  148. h = append(h, handlers...)
  149. handlers = h
  150. }
  151. validateHandlers(handlers)
  152. return r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) {
  153. c := r.m.createContext(resp, req)
  154. c.params = params
  155. c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
  156. c.handlers = append(c.handlers, r.m.handlers...)
  157. c.handlers = append(c.handlers, handlers...)
  158. c.run()
  159. })
  160. }
  161. func (r *Router) Group(pattern string, fn func(), h ...Handler) {
  162. r.groups = append(r.groups, group{pattern, h})
  163. fn()
  164. r.groups = r.groups[:len(r.groups)-1]
  165. }
  166. // Get is a shortcut for r.Handle("GET", pattern, handlers)
  167. func (r *Router) Get(pattern string, h ...Handler) (leaf *Route) {
  168. leaf = r.Handle("GET", pattern, h)
  169. if r.autoHead {
  170. r.Head(pattern, h...)
  171. }
  172. return leaf
  173. }
  174. // Patch is a shortcut for r.Handle("PATCH", pattern, handlers)
  175. func (r *Router) Patch(pattern string, h ...Handler) *Route {
  176. return r.Handle("PATCH", pattern, h)
  177. }
  178. // Post is a shortcut for r.Handle("POST", pattern, handlers)
  179. func (r *Router) Post(pattern string, h ...Handler) *Route {
  180. return r.Handle("POST", pattern, h)
  181. }
  182. // Put is a shortcut for r.Handle("PUT", pattern, handlers)
  183. func (r *Router) Put(pattern string, h ...Handler) *Route {
  184. return r.Handle("PUT", pattern, h)
  185. }
  186. // Delete is a shortcut for r.Handle("DELETE", pattern, handlers)
  187. func (r *Router) Delete(pattern string, h ...Handler) *Route {
  188. return r.Handle("DELETE", pattern, h)
  189. }
  190. // Options is a shortcut for r.Handle("OPTIONS", pattern, handlers)
  191. func (r *Router) Options(pattern string, h ...Handler) *Route {
  192. return r.Handle("OPTIONS", pattern, h)
  193. }
  194. // Head is a shortcut for r.Handle("HEAD", pattern, handlers)
  195. func (r *Router) Head(pattern string, h ...Handler) *Route {
  196. return r.Handle("HEAD", pattern, h)
  197. }
  198. // Any is a shortcut for r.Handle("*", pattern, handlers)
  199. func (r *Router) Any(pattern string, h ...Handler) *Route {
  200. return r.Handle("*", pattern, h)
  201. }
  202. // Route is a shortcut for same handlers but different HTTP methods.
  203. //
  204. // Example:
  205. // m.Route("/", "GET,POST", h)
  206. func (r *Router) Route(pattern, methods string, h ...Handler) (route *Route) {
  207. for _, m := range strings.Split(methods, ",") {
  208. route = r.Handle(strings.TrimSpace(m), pattern, h)
  209. }
  210. return route
  211. }
  212. // Combo returns a combo router.
  213. func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
  214. return &ComboRouter{r, pattern, h, map[string]bool{}, nil}
  215. }
  216. // Configurable http.HandlerFunc which is called when no matching route is
  217. // found. If it is not set, http.NotFound is used.
  218. // Be sure to set 404 response code in your handler.
  219. func (r *Router) NotFound(handlers ...Handler) {
  220. validateHandlers(handlers)
  221. r.notFound = func(rw http.ResponseWriter, req *http.Request) {
  222. c := r.m.createContext(rw, req)
  223. c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
  224. c.handlers = append(c.handlers, r.m.handlers...)
  225. c.handlers = append(c.handlers, handlers...)
  226. c.run()
  227. }
  228. }
  229. // Configurable handler which is called when route handler returns
  230. // error. If it is not set, default handler is used.
  231. // Be sure to set 500 response code in your handler.
  232. func (r *Router) InternalServerError(handlers ...Handler) {
  233. validateHandlers(handlers)
  234. r.internalServerError = func(c *Context, err error) {
  235. c.index = 0
  236. c.handlers = handlers
  237. c.Map(err)
  238. c.run()
  239. }
  240. }
  241. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  242. if t, ok := r.routers[req.Method]; ok {
  243. h, p, ok := t.Match(req.URL.Path)
  244. if ok {
  245. if splat, ok := p["*0"]; ok {
  246. p["*"] = splat // Easy name.
  247. }
  248. h(rw, req, p)
  249. return
  250. }
  251. }
  252. r.notFound(rw, req)
  253. }
  254. // URLFor builds path part of URL by given pair values.
  255. func (r *Router) URLFor(name string, pairs ...string) string {
  256. leaf, ok := r.namedRoutes[name]
  257. if !ok {
  258. panic("route with given name does not exists: " + name)
  259. }
  260. return leaf.URLPath(pairs...)
  261. }
  262. // ComboRouter represents a combo router.
  263. type ComboRouter struct {
  264. router *Router
  265. pattern string
  266. handlers []Handler
  267. methods map[string]bool // Registered methods.
  268. lastRoute *Route
  269. }
  270. func (cr *ComboRouter) checkMethod(name string) {
  271. if cr.methods[name] {
  272. panic("method '" + name + "' has already been registered")
  273. }
  274. cr.methods[name] = true
  275. }
  276. func (cr *ComboRouter) route(fn func(string, ...Handler) *Route, method string, h ...Handler) *ComboRouter {
  277. cr.checkMethod(method)
  278. cr.lastRoute = fn(cr.pattern, append(cr.handlers, h...)...)
  279. return cr
  280. }
  281. func (cr *ComboRouter) Get(h ...Handler) *ComboRouter {
  282. return cr.route(cr.router.Get, "GET", h...)
  283. }
  284. func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter {
  285. return cr.route(cr.router.Patch, "PATCH", h...)
  286. }
  287. func (cr *ComboRouter) Post(h ...Handler) *ComboRouter {
  288. return cr.route(cr.router.Post, "POST", h...)
  289. }
  290. func (cr *ComboRouter) Put(h ...Handler) *ComboRouter {
  291. return cr.route(cr.router.Put, "PUT", h...)
  292. }
  293. func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter {
  294. return cr.route(cr.router.Delete, "DELETE", h...)
  295. }
  296. func (cr *ComboRouter) Options(h ...Handler) *ComboRouter {
  297. return cr.route(cr.router.Options, "OPTIONS", h...)
  298. }
  299. func (cr *ComboRouter) Head(h ...Handler) *ComboRouter {
  300. return cr.route(cr.router.Head, "HEAD", h...)
  301. }
  302. // Name sets name of ComboRouter route.
  303. func (cr *ComboRouter) Name(name string) {
  304. if cr.lastRoute == nil {
  305. panic("no corresponding route to be named")
  306. }
  307. cr.lastRoute.Name(name)
  308. }