Micro & pluggable web framework for Go
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.

110 lines
2.3 KiB

  1. // Copyright 2015 The Tango Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tango
  5. type groupRouter struct {
  6. methods []string
  7. url string
  8. c interface{}
  9. }
  10. type Group struct {
  11. routers []groupRouter
  12. handlers []Handler
  13. }
  14. func NewGroup() *Group {
  15. return &Group{
  16. routers: make([]groupRouter, 0),
  17. handlers: make([]Handler, 0),
  18. }
  19. }
  20. func (g *Group) Use(handlers ...Handler) {
  21. g.handlers = append(g.handlers, handlers...)
  22. }
  23. func (g *Group) Get(url string, c interface{}) {
  24. g.Route([]string{"GET", "HEAD:Get"}, url, c)
  25. }
  26. func (g *Group) Post(url string, c interface{}) {
  27. g.Route([]string{"POST"}, url, c)
  28. }
  29. func (g *Group) Head(url string, c interface{}) {
  30. g.Route([]string{"HEAD"}, url, c)
  31. }
  32. func (g *Group) Options(url string, c interface{}) {
  33. g.Route([]string{"OPTIONS"}, url, c)
  34. }
  35. func (g *Group) Trace(url string, c interface{}) {
  36. g.Route([]string{"TRACE"}, url, c)
  37. }
  38. func (g *Group) Patch(url string, c interface{}) {
  39. g.Route([]string{"PATCH"}, url, c)
  40. }
  41. func (g *Group) Delete(url string, c interface{}) {
  42. g.Route([]string{"DELETE"}, url, c)
  43. }
  44. func (g *Group) Put(url string, c interface{}) {
  45. g.Route([]string{"PUT"}, url, c)
  46. }
  47. func (g *Group) Any(url string, c interface{}) {
  48. g.Route(SupportMethods, url, c)
  49. g.Route([]string{"HEAD:Get"}, url, c)
  50. }
  51. func (g *Group) Route(methods []string, url string, c interface{}) {
  52. g.routers = append(g.routers, groupRouter{methods, url, c})
  53. }
  54. func (g *Group) Group(p string, o interface{}) {
  55. gr := getGroup(o)
  56. for _, gchild := range gr.routers {
  57. g.Route(gchild.methods, joinRoute(p, gchild.url), gchild.c)
  58. }
  59. }
  60. func getGroup(o interface{}) *Group {
  61. var g *Group
  62. var gf func(*Group)
  63. var ok bool
  64. if g, ok = o.(*Group); ok {
  65. } else if gf, ok = o.(func(*Group)); ok {
  66. g = NewGroup()
  67. gf(g)
  68. } else {
  69. panic("not allowed group parameter")
  70. }
  71. return g
  72. }
  73. func joinRoute(p, url string) string {
  74. if len(p) == 0 || p == "/" {
  75. return url
  76. }
  77. return p + url
  78. }
  79. func (t *Tango) addGroup(p string, g *Group) {
  80. for _, r := range g.routers {
  81. t.Route(r.methods, joinRoute(p, r.url), r.c)
  82. }
  83. for _, h := range g.handlers {
  84. t.Use(Prefix(p, h))
  85. }
  86. }
  87. func (t *Tango) Group(p string, o interface{}) {
  88. t.addGroup(p, getGroup(o))
  89. }