curly_route.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package restful
  2. // Copyright 2013 Ernest Micklei. All rights reserved.
  3. // Use of this source code is governed by a license
  4. // that can be found in the LICENSE file.
  5. // curlyRoute exits for sorting Routes by the CurlyRouter based on number of parameters and number of static path elements.
  6. type curlyRoute struct {
  7. route Route
  8. paramCount int
  9. staticCount int
  10. }
  11. // sortableCurlyRoutes orders by most parameters and path elements first.
  12. type sortableCurlyRoutes []curlyRoute
  13. func (s *sortableCurlyRoutes) add(route curlyRoute) {
  14. *s = append(*s, route)
  15. }
  16. func (s sortableCurlyRoutes) routes() (routes []Route) {
  17. routes = make([]Route, 0, len(s))
  18. for _, each := range s {
  19. routes = append(routes, each.route) // TODO change return type
  20. }
  21. return routes
  22. }
  23. func (s sortableCurlyRoutes) Len() int {
  24. return len(s)
  25. }
  26. func (s sortableCurlyRoutes) Swap(i, j int) {
  27. s[i], s[j] = s[j], s[i]
  28. }
  29. func (s sortableCurlyRoutes) Less(i, j int) bool {
  30. a := s[j]
  31. b := s[i]
  32. // primary key
  33. if a.staticCount < b.staticCount {
  34. return true
  35. }
  36. if a.staticCount > b.staticCount {
  37. return false
  38. }
  39. // secundary key
  40. if a.paramCount < b.paramCount {
  41. return true
  42. }
  43. if a.paramCount > b.paramCount {
  44. return false
  45. }
  46. return a.route.Path < b.route.Path
  47. }