You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

360 lines
9.3 KiB

  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 = append(r.m.handlers, handlers...)
  224. c.run()
  225. }
  226. }
  227. // Configurable handler which is called when route handler returns
  228. // error. If it is not set, default handler is used.
  229. // Be sure to set 500 response code in your handler.
  230. func (r *Router) InternalServerError(handlers ...Handler) {
  231. validateHandlers(handlers)
  232. r.internalServerError = func(c *Context, err error) {
  233. c.index = 0
  234. c.handlers = handlers
  235. c.Map(err)
  236. c.run()
  237. }
  238. }
  239. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  240. if t, ok := r.routers[req.Method]; ok {
  241. h, p, ok := t.Match(req.URL.Path)
  242. if ok {
  243. if splat, ok := p["*0"]; ok {
  244. p["*"] = splat // Easy name.
  245. }
  246. h(rw, req, p)
  247. return
  248. }
  249. }
  250. r.notFound(rw, req)
  251. }
  252. // URLFor builds path part of URL by given pair values.
  253. func (r *Router) URLFor(name string, pairs ...string) string {
  254. leaf, ok := r.namedRoutes[name]
  255. if !ok {
  256. panic("route with given name does not exists: " + name)
  257. }
  258. return leaf.URLPath(pairs...)
  259. }
  260. // ComboRouter represents a combo router.
  261. type ComboRouter struct {
  262. router *Router
  263. pattern string
  264. handlers []Handler
  265. methods map[string]bool // Registered methods.
  266. lastRoute *Route
  267. }
  268. func (cr *ComboRouter) checkMethod(name string) {
  269. if cr.methods[name] {
  270. panic("method '" + name + "' has already been registered")
  271. }
  272. cr.methods[name] = true
  273. }
  274. func (cr *ComboRouter) route(fn func(string, ...Handler) *Route, method string, h ...Handler) *ComboRouter {
  275. cr.checkMethod(method)
  276. cr.lastRoute = fn(cr.pattern, append(cr.handlers, h...)...)
  277. return cr
  278. }
  279. func (cr *ComboRouter) Get(h ...Handler) *ComboRouter {
  280. return cr.route(cr.router.Get, "GET", h...)
  281. }
  282. func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter {
  283. return cr.route(cr.router.Patch, "PATCH", h...)
  284. }
  285. func (cr *ComboRouter) Post(h ...Handler) *ComboRouter {
  286. return cr.route(cr.router.Post, "POST", h...)
  287. }
  288. func (cr *ComboRouter) Put(h ...Handler) *ComboRouter {
  289. return cr.route(cr.router.Put, "PUT", h...)
  290. }
  291. func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter {
  292. return cr.route(cr.router.Delete, "DELETE", h...)
  293. }
  294. func (cr *ComboRouter) Options(h ...Handler) *ComboRouter {
  295. return cr.route(cr.router.Options, "OPTIONS", h...)
  296. }
  297. func (cr *ComboRouter) Head(h ...Handler) *ComboRouter {
  298. return cr.route(cr.router.Head, "HEAD", h...)
  299. }
  300. // Name sets name of ComboRouter route.
  301. func (cr *ComboRouter) Name(name string) {
  302. if cr.lastRoute == nil {
  303. panic("no corresponding route to be named")
  304. }
  305. cr.lastRoute.Name(name)
  306. }