route_register.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package api
  2. import (
  3. "net/http"
  4. macaron "gopkg.in/macaron.v1"
  5. )
  6. type Router interface {
  7. Route(pattern, method string, handlers ...macaron.Handler)
  8. }
  9. type RouteRegister interface {
  10. Get(string, ...macaron.Handler)
  11. Post(string, ...macaron.Handler)
  12. Delete(string, ...macaron.Handler)
  13. Put(string, ...macaron.Handler)
  14. Group(string, func(RouteRegister), ...macaron.Handler)
  15. Register(Router)
  16. }
  17. func newRouteRegister() RouteRegister {
  18. return &routeRegister{
  19. prefix: "",
  20. routes: []route{},
  21. subfixHandlers: []macaron.Handler{},
  22. }
  23. }
  24. type route struct {
  25. method string
  26. pattern string
  27. handlers []macaron.Handler
  28. }
  29. type routeRegister struct {
  30. prefix string
  31. subfixHandlers []macaron.Handler
  32. routes []route
  33. groups []*routeRegister
  34. }
  35. func (rr *routeRegister) Group(pattern string, fn func(rr RouteRegister), handlers ...macaron.Handler) {
  36. group := &routeRegister{
  37. prefix: rr.prefix + pattern,
  38. subfixHandlers: append(rr.subfixHandlers, handlers...),
  39. routes: []route{},
  40. }
  41. fn(group)
  42. rr.groups = append(rr.groups, group)
  43. }
  44. func (rr *routeRegister) Register(router Router) {
  45. for _, r := range rr.routes {
  46. router.Route(r.pattern, r.method, r.handlers...)
  47. }
  48. for _, g := range rr.groups {
  49. g.Register(router)
  50. }
  51. }
  52. func (rr *routeRegister) route(pattern, method string, handlers ...macaron.Handler) {
  53. rr.routes = append(rr.routes, route{
  54. method: method,
  55. pattern: rr.prefix + pattern,
  56. handlers: append(rr.subfixHandlers, handlers...),
  57. })
  58. }
  59. func (rr *routeRegister) Get(pattern string, handlers ...macaron.Handler) {
  60. rr.route(pattern, http.MethodGet, handlers...)
  61. }
  62. func (rr *routeRegister) Post(pattern string, handlers ...macaron.Handler) {
  63. rr.route(pattern, http.MethodPost, handlers...)
  64. }
  65. func (rr *routeRegister) Delete(pattern string, handlers ...macaron.Handler) {
  66. rr.route(pattern, http.MethodDelete, handlers...)
  67. }
  68. func (rr *routeRegister) Put(pattern string, handlers ...macaron.Handler) {
  69. rr.route(pattern, http.MethodPut, handlers...)
  70. }