router.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // handlerWrapper is used to wrap arbitrary function from Handler to inject.FastInvoker.
  74. handlerWrapper func(Handler) Handler
  75. }
  76. func NewRouter() *Router {
  77. return &Router{
  78. routers: make(map[string]*Tree),
  79. routeMap: NewRouteMap(),
  80. namedRoutes: make(map[string]*Leaf),
  81. }
  82. }
  83. // SetAutoHead sets the value who determines whether add HEAD method automatically
  84. // when GET method is added. Combo router will not be affected by this value.
  85. func (r *Router) SetAutoHead(v bool) {
  86. r.autoHead = v
  87. }
  88. type Params map[string]string
  89. // Handle is a function that can be registered to a route to handle HTTP requests.
  90. // Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
  91. type Handle func(http.ResponseWriter, *http.Request, Params)
  92. // Route represents a wrapper of leaf route and upper level router.
  93. type Route struct {
  94. router *Router
  95. leaf *Leaf
  96. }
  97. // Name sets name of route.
  98. func (r *Route) Name(name string) {
  99. if len(name) == 0 {
  100. panic("route name cannot be empty")
  101. } else if r.router.namedRoutes[name] != nil {
  102. panic("route with given name already exists")
  103. }
  104. r.router.namedRoutes[name] = r.leaf
  105. }
  106. // handle adds new route to the router tree.
  107. func (r *Router) handle(method, pattern string, handle Handle) *Route {
  108. method = strings.ToUpper(method)
  109. var leaf *Leaf
  110. // Prevent duplicate routes.
  111. if leaf = r.getLeaf(method, pattern); leaf != nil {
  112. return &Route{r, leaf}
  113. }
  114. // Validate HTTP methods.
  115. if !_HTTP_METHODS[method] && method != "*" {
  116. panic("unknown HTTP method: " + method)
  117. }
  118. // Generate methods need register.
  119. methods := make(map[string]bool)
  120. if method == "*" {
  121. for m := range _HTTP_METHODS {
  122. methods[m] = true
  123. }
  124. } else {
  125. methods[method] = true
  126. }
  127. // Add to router tree.
  128. for m := range methods {
  129. if t, ok := r.routers[m]; ok {
  130. leaf = t.Add(pattern, handle)
  131. } else {
  132. t := NewTree()
  133. leaf = t.Add(pattern, handle)
  134. r.routers[m] = t
  135. }
  136. r.add(m, pattern, leaf)
  137. }
  138. return &Route{r, leaf}
  139. }
  140. // Handle registers a new request handle with the given pattern, method and handlers.
  141. func (r *Router) Handle(method string, pattern string, handlers []Handler) *Route {
  142. if len(r.groups) > 0 {
  143. groupPattern := ""
  144. h := make([]Handler, 0)
  145. for _, g := range r.groups {
  146. groupPattern += g.pattern
  147. h = append(h, g.handlers...)
  148. }
  149. pattern = groupPattern + pattern
  150. h = append(h, handlers...)
  151. handlers = h
  152. }
  153. handlers = validateAndWrapHandlers(handlers, r.handlerWrapper)
  154. return r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) {
  155. c := r.m.createContext(resp, req)
  156. c.params = params
  157. c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
  158. c.handlers = append(c.handlers, r.m.handlers...)
  159. c.handlers = append(c.handlers, handlers...)
  160. c.run()
  161. })
  162. }
  163. func (r *Router) Group(pattern string, fn func(), h ...Handler) {
  164. r.groups = append(r.groups, group{pattern, h})
  165. fn()
  166. r.groups = r.groups[:len(r.groups)-1]
  167. }
  168. // Get is a shortcut for r.Handle("GET", pattern, handlers)
  169. func (r *Router) Get(pattern string, h ...Handler) (leaf *Route) {
  170. leaf = r.Handle("GET", pattern, h)
  171. if r.autoHead {
  172. r.Head(pattern, h...)
  173. }
  174. return leaf
  175. }
  176. // Patch is a shortcut for r.Handle("PATCH", pattern, handlers)
  177. func (r *Router) Patch(pattern string, h ...Handler) *Route {
  178. return r.Handle("PATCH", pattern, h)
  179. }
  180. // Post is a shortcut for r.Handle("POST", pattern, handlers)
  181. func (r *Router) Post(pattern string, h ...Handler) *Route {
  182. return r.Handle("POST", pattern, h)
  183. }
  184. // Put is a shortcut for r.Handle("PUT", pattern, handlers)
  185. func (r *Router) Put(pattern string, h ...Handler) *Route {
  186. return r.Handle("PUT", pattern, h)
  187. }
  188. // Delete is a shortcut for r.Handle("DELETE", pattern, handlers)
  189. func (r *Router) Delete(pattern string, h ...Handler) *Route {
  190. return r.Handle("DELETE", pattern, h)
  191. }
  192. // Options is a shortcut for r.Handle("OPTIONS", pattern, handlers)
  193. func (r *Router) Options(pattern string, h ...Handler) *Route {
  194. return r.Handle("OPTIONS", pattern, h)
  195. }
  196. // Head is a shortcut for r.Handle("HEAD", pattern, handlers)
  197. func (r *Router) Head(pattern string, h ...Handler) *Route {
  198. return r.Handle("HEAD", pattern, h)
  199. }
  200. // Any is a shortcut for r.Handle("*", pattern, handlers)
  201. func (r *Router) Any(pattern string, h ...Handler) *Route {
  202. return r.Handle("*", pattern, h)
  203. }
  204. // Route is a shortcut for same handlers but different HTTP methods.
  205. //
  206. // Example:
  207. // m.Route("/", "GET,POST", h)
  208. func (r *Router) Route(pattern, methods string, h ...Handler) (route *Route) {
  209. for _, m := range strings.Split(methods, ",") {
  210. route = r.Handle(strings.TrimSpace(m), pattern, h)
  211. }
  212. return route
  213. }
  214. // Combo returns a combo router.
  215. func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
  216. return &ComboRouter{r, pattern, h, map[string]bool{}, nil}
  217. }
  218. // NotFound configurates http.HandlerFunc which is called when no matching route is
  219. // found. If it is not set, http.NotFound is used.
  220. // Be sure to set 404 response code in your handler.
  221. func (r *Router) NotFound(handlers ...Handler) {
  222. handlers = validateAndWrapHandlers(handlers)
  223. r.notFound = func(rw http.ResponseWriter, req *http.Request) {
  224. c := r.m.createContext(rw, req)
  225. c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
  226. c.handlers = append(c.handlers, r.m.handlers...)
  227. c.handlers = append(c.handlers, handlers...)
  228. c.run()
  229. }
  230. }
  231. // InternalServerError configurates handler which is called when route handler returns
  232. // error. If it is not set, default handler is used.
  233. // Be sure to set 500 response code in your handler.
  234. func (r *Router) InternalServerError(handlers ...Handler) {
  235. handlers = validateAndWrapHandlers(handlers)
  236. r.internalServerError = func(c *Context, err error) {
  237. c.index = 0
  238. c.handlers = handlers
  239. c.Map(err)
  240. c.run()
  241. }
  242. }
  243. // SetHandlerWrapper sets handlerWrapper for the router.
  244. func (r *Router) SetHandlerWrapper(f func(Handler) Handler) {
  245. r.handlerWrapper = f
  246. }
  247. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  248. if t, ok := r.routers[req.Method]; ok {
  249. h, p, ok := t.Match(req.URL.Path)
  250. if ok {
  251. if splat, ok := p["*0"]; ok {
  252. p["*"] = splat // Easy name.
  253. }
  254. h(rw, req, p)
  255. return
  256. }
  257. }
  258. r.notFound(rw, req)
  259. }
  260. // URLFor builds path part of URL by given pair values.
  261. func (r *Router) URLFor(name string, pairs ...string) string {
  262. leaf, ok := r.namedRoutes[name]
  263. if !ok {
  264. panic("route with given name does not exists: " + name)
  265. }
  266. return leaf.URLPath(pairs...)
  267. }
  268. // ComboRouter represents a combo router.
  269. type ComboRouter struct {
  270. router *Router
  271. pattern string
  272. handlers []Handler
  273. methods map[string]bool // Registered methods.
  274. lastRoute *Route
  275. }
  276. func (cr *ComboRouter) checkMethod(name string) {
  277. if cr.methods[name] {
  278. panic("method '" + name + "' has already been registered")
  279. }
  280. cr.methods[name] = true
  281. }
  282. func (cr *ComboRouter) route(fn func(string, ...Handler) *Route, method string, h ...Handler) *ComboRouter {
  283. cr.checkMethod(method)
  284. cr.lastRoute = fn(cr.pattern, append(cr.handlers, h...)...)
  285. return cr
  286. }
  287. func (cr *ComboRouter) Get(h ...Handler) *ComboRouter {
  288. return cr.route(cr.router.Get, "GET", h...)
  289. }
  290. func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter {
  291. return cr.route(cr.router.Patch, "PATCH", h...)
  292. }
  293. func (cr *ComboRouter) Post(h ...Handler) *ComboRouter {
  294. return cr.route(cr.router.Post, "POST", h...)
  295. }
  296. func (cr *ComboRouter) Put(h ...Handler) *ComboRouter {
  297. return cr.route(cr.router.Put, "PUT", h...)
  298. }
  299. func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter {
  300. return cr.route(cr.router.Delete, "DELETE", h...)
  301. }
  302. func (cr *ComboRouter) Options(h ...Handler) *ComboRouter {
  303. return cr.route(cr.router.Options, "OPTIONS", h...)
  304. }
  305. func (cr *ComboRouter) Head(h ...Handler) *ComboRouter {
  306. return cr.route(cr.router.Head, "HEAD", h...)
  307. }
  308. // Name sets name of ComboRouter route.
  309. func (cr *ComboRouter) Name(name string) {
  310. if cr.lastRoute == nil {
  311. panic("no corresponding route to be named")
  312. }
  313. cr.lastRoute.Name(name)
  314. }