1
0

router.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package vhost
  2. import (
  3. "sort"
  4. "strings"
  5. "sync"
  6. )
  7. type VhostRouters struct {
  8. RouterByDomain map[string][]*VhostRouter
  9. mutex sync.RWMutex
  10. }
  11. type VhostRouter struct {
  12. domain string
  13. location string
  14. payload interface{}
  15. }
  16. func NewVhostRouters() *VhostRouters {
  17. return &VhostRouters{
  18. RouterByDomain: make(map[string][]*VhostRouter),
  19. }
  20. }
  21. func (r *VhostRouters) Add(domain, location string, payload interface{}) {
  22. r.mutex.Lock()
  23. defer r.mutex.Unlock()
  24. vrs, found := r.RouterByDomain[domain]
  25. if !found {
  26. vrs = make([]*VhostRouter, 0, 1)
  27. }
  28. vr := &VhostRouter{
  29. domain: domain,
  30. location: location,
  31. payload: payload,
  32. }
  33. vrs = append(vrs, vr)
  34. sort.Sort(sort.Reverse(ByLocation(vrs)))
  35. r.RouterByDomain[domain] = vrs
  36. }
  37. func (r *VhostRouters) Del(domain, location string) {
  38. r.mutex.Lock()
  39. defer r.mutex.Unlock()
  40. vrs, found := r.RouterByDomain[domain]
  41. if !found {
  42. return
  43. }
  44. for i, vr := range vrs {
  45. if vr.location == location {
  46. if len(vrs) > i+1 {
  47. r.RouterByDomain[domain] = append(vrs[:i], vrs[i+1:]...)
  48. } else {
  49. r.RouterByDomain[domain] = vrs[:i]
  50. }
  51. }
  52. }
  53. }
  54. func (r *VhostRouters) Get(host, path string) (vr *VhostRouter, exist bool) {
  55. r.mutex.RLock()
  56. defer r.mutex.RUnlock()
  57. vrs, found := r.RouterByDomain[host]
  58. if !found {
  59. return
  60. }
  61. // can't support load balance, will to do
  62. for _, vr = range vrs {
  63. if strings.HasPrefix(path, vr.location) {
  64. return vr, true
  65. }
  66. }
  67. return
  68. }
  69. func (r *VhostRouters) Exist(host, path string) (vr *VhostRouter, exist bool) {
  70. r.mutex.RLock()
  71. defer r.mutex.RUnlock()
  72. vrs, found := r.RouterByDomain[host]
  73. if !found {
  74. return
  75. }
  76. for _, vr = range vrs {
  77. if path == vr.location {
  78. return vr, true
  79. }
  80. }
  81. return
  82. }
  83. // sort by location
  84. type ByLocation []*VhostRouter
  85. func (a ByLocation) Len() int {
  86. return len(a)
  87. }
  88. func (a ByLocation) Swap(i, j int) {
  89. a[i], a[j] = a[j], a[i]
  90. }
  91. func (a ByLocation) Less(i, j int) bool {
  92. return strings.Compare(a[i].location, a[j].location) < 0
  93. }