router.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright 2014 Unknwon
  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. "github.com/Unknwon/com"
  20. )
  21. var (
  22. // Known HTTP methods.
  23. _HTTP_METHODS = map[string]bool{
  24. "GET": true,
  25. "POST": true,
  26. "PUT": true,
  27. "DELETE": true,
  28. "PATCH": true,
  29. "OPTIONS": true,
  30. "HEAD": true,
  31. }
  32. )
  33. // routeMap represents a thread-safe map for route tree.
  34. type routeMap struct {
  35. lock sync.RWMutex
  36. routes map[string]map[string]bool
  37. }
  38. // NewRouteMap initializes and returns a new routeMap.
  39. func NewRouteMap() *routeMap {
  40. rm := &routeMap{
  41. routes: make(map[string]map[string]bool),
  42. }
  43. for m := range _HTTP_METHODS {
  44. rm.routes[m] = make(map[string]bool)
  45. }
  46. return rm
  47. }
  48. // isExist returns true if a route has been registered.
  49. func (rm *routeMap) isExist(method, pattern string) bool {
  50. rm.lock.RLock()
  51. defer rm.lock.RUnlock()
  52. return rm.routes[method][pattern]
  53. }
  54. // add adds new route to route tree map.
  55. func (rm *routeMap) add(method, pattern string) {
  56. rm.lock.Lock()
  57. defer rm.lock.Unlock()
  58. rm.routes[method][pattern] = true
  59. }
  60. type group struct {
  61. pattern string
  62. handlers []Handler
  63. }
  64. // Router represents a Macaron router layer.
  65. type Router struct {
  66. m *Macaron
  67. routers map[string]*Tree
  68. *routeMap
  69. groups []group
  70. notFound http.HandlerFunc
  71. }
  72. func NewRouter() *Router {
  73. return &Router{
  74. routers: make(map[string]*Tree),
  75. routeMap: NewRouteMap(),
  76. }
  77. }
  78. type Params map[string]string
  79. // Handle is a function that can be registered to a route to handle HTTP requests.
  80. // Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
  81. type Handle func(http.ResponseWriter, *http.Request, Params)
  82. // handle adds new route to the router tree.
  83. func (r *Router) handle(method, pattern string, handle Handle) {
  84. method = strings.ToUpper(method)
  85. // Prevent duplicate routes.
  86. if r.isExist(method, pattern) {
  87. return
  88. }
  89. // Validate HTTP methods.
  90. if !_HTTP_METHODS[method] && method != "*" {
  91. panic("unknown HTTP method: " + method)
  92. }
  93. // Generate methods need register.
  94. methods := make(map[string]bool)
  95. if method == "*" {
  96. for m := range _HTTP_METHODS {
  97. methods[m] = true
  98. }
  99. } else {
  100. methods[method] = true
  101. }
  102. // Add to router tree.
  103. for m := range methods {
  104. if t, ok := r.routers[m]; ok {
  105. t.AddRouter(pattern, handle)
  106. } else {
  107. t := NewTree()
  108. t.AddRouter(pattern, handle)
  109. r.routers[m] = t
  110. }
  111. r.add(m, pattern)
  112. }
  113. }
  114. // Handle registers a new request handle with the given pattern, method and handlers.
  115. func (r *Router) Handle(method string, pattern string, handlers []Handler) {
  116. if len(r.groups) > 0 {
  117. groupPattern := ""
  118. h := make([]Handler, 0)
  119. for _, g := range r.groups {
  120. groupPattern += g.pattern
  121. h = append(h, g.handlers...)
  122. }
  123. pattern = groupPattern + pattern
  124. h = append(h, handlers...)
  125. handlers = h
  126. }
  127. validateHandlers(handlers)
  128. r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) {
  129. c := r.m.createContext(resp, req)
  130. c.params = params
  131. c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
  132. c.handlers = append(c.handlers, r.m.handlers...)
  133. c.handlers = append(c.handlers, handlers...)
  134. c.run()
  135. })
  136. }
  137. func (r *Router) Group(pattern string, fn func(), h ...Handler) {
  138. r.groups = append(r.groups, group{pattern, h})
  139. fn()
  140. r.groups = r.groups[:len(r.groups)-1]
  141. }
  142. // Get is a shortcut for r.Handle("GET", pattern, handlers)
  143. func (r *Router) Get(pattern string, h ...Handler) {
  144. r.Handle("GET", pattern, h)
  145. }
  146. // Patch is a shortcut for r.Handle("PATCH", pattern, handlers)
  147. func (r *Router) Patch(pattern string, h ...Handler) {
  148. r.Handle("PATCH", pattern, h)
  149. }
  150. // Post is a shortcut for r.Handle("POST", pattern, handlers)
  151. func (r *Router) Post(pattern string, h ...Handler) {
  152. r.Handle("POST", pattern, h)
  153. }
  154. // Put is a shortcut for r.Handle("PUT", pattern, handlers)
  155. func (r *Router) Put(pattern string, h ...Handler) {
  156. r.Handle("PUT", pattern, h)
  157. }
  158. // Delete is a shortcut for r.Handle("DELETE", pattern, handlers)
  159. func (r *Router) Delete(pattern string, h ...Handler) {
  160. r.Handle("DELETE", pattern, h)
  161. }
  162. // Options is a shortcut for r.Handle("OPTIONS", pattern, handlers)
  163. func (r *Router) Options(pattern string, h ...Handler) {
  164. r.Handle("OPTIONS", pattern, h)
  165. }
  166. // Head is a shortcut for r.Handle("HEAD", pattern, handlers)
  167. func (r *Router) Head(pattern string, h ...Handler) {
  168. r.Handle("HEAD", pattern, h)
  169. }
  170. // Any is a shortcut for r.Handle("*", pattern, handlers)
  171. func (r *Router) Any(pattern string, h ...Handler) {
  172. r.Handle("*", pattern, h)
  173. }
  174. // Route is a shortcut for same handlers but different HTTP methods.
  175. //
  176. // Example:
  177. // m.Route("/", "GET,POST", h)
  178. func (r *Router) Route(pattern, methods string, h ...Handler) {
  179. for _, m := range strings.Split(methods, ",") {
  180. r.Handle(strings.TrimSpace(m), pattern, h)
  181. }
  182. }
  183. // Combo returns a combo router.
  184. func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
  185. return &ComboRouter{r, pattern, h, map[string]bool{}}
  186. }
  187. // Configurable http.HandlerFunc which is called when no matching route is
  188. // found. If it is not set, http.NotFound is used.
  189. // Be sure to set 404 response code in your handler.
  190. func (r *Router) NotFound(handlers ...Handler) {
  191. r.notFound = func(rw http.ResponseWriter, req *http.Request) {
  192. c := r.m.createContext(rw, req)
  193. c.handlers = append(r.m.handlers, handlers...)
  194. c.run()
  195. }
  196. }
  197. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  198. if t, ok := r.routers[req.Method]; ok {
  199. h, p := t.Match(req.URL.Path)
  200. if h != nil {
  201. if splat, ok := p[":splat"]; ok {
  202. p["*"] = p[":splat"] // Better name.
  203. splatlist := strings.Split(splat, "/")
  204. for k, v := range splatlist {
  205. p[com.ToStr(k)] = v
  206. }
  207. }
  208. h(rw, req, p)
  209. return
  210. }
  211. }
  212. r.notFound(rw, req)
  213. }
  214. // ComboRouter represents a combo router.
  215. type ComboRouter struct {
  216. router *Router
  217. pattern string
  218. handlers []Handler
  219. methods map[string]bool // Registered methods.
  220. }
  221. func (cr *ComboRouter) checkMethod(name string) {
  222. if cr.methods[name] {
  223. panic("method '" + name + "' has already been registered")
  224. }
  225. cr.methods[name] = true
  226. }
  227. func (cr *ComboRouter) route(fn func(string, ...Handler), method string, h ...Handler) *ComboRouter {
  228. cr.checkMethod(method)
  229. fn(cr.pattern, append(cr.handlers, h...)...)
  230. return cr
  231. }
  232. func (cr *ComboRouter) Get(h ...Handler) *ComboRouter {
  233. return cr.route(cr.router.Get, "GET", h...)
  234. }
  235. func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter {
  236. return cr.route(cr.router.Patch, "PATCH", h...)
  237. }
  238. func (cr *ComboRouter) Post(h ...Handler) *ComboRouter {
  239. return cr.route(cr.router.Post, "POST", h...)
  240. }
  241. func (cr *ComboRouter) Put(h ...Handler) *ComboRouter {
  242. return cr.route(cr.router.Put, "PUT", h...)
  243. }
  244. func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter {
  245. return cr.route(cr.router.Delete, "DELETE", h...)
  246. }
  247. func (cr *ComboRouter) Options(h ...Handler) *ComboRouter {
  248. return cr.route(cr.router.Options, "OPTIONS", h...)
  249. }
  250. func (cr *ComboRouter) Head(h ...Handler) *ComboRouter {
  251. return cr.route(cr.router.Head, "HEAD", h...)
  252. }