-
-
Notifications
You must be signed in to change notification settings - Fork 13k
/
router.go
136 lines (110 loc) · 2.42 KB
/
router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package vhost
import (
"cmp"
"errors"
"slices"
"strings"
"sync"
)
var ErrRouterConfigConflict = errors.New("router config conflict")
type routerByHTTPUser map[string][]*Router
type Routers struct {
indexByDomain map[string]routerByHTTPUser
mutex sync.RWMutex
}
type Router struct {
domain string
location string
httpUser string
// store any object here
payload interface{}
}
func NewRouters() *Routers {
return &Routers{
indexByDomain: make(map[string]routerByHTTPUser),
}
}
func (r *Routers) Add(domain, location, httpUser string, payload interface{}) error {
domain = strings.ToLower(domain)
r.mutex.Lock()
defer r.mutex.Unlock()
if _, exist := r.exist(domain, location, httpUser); exist {
return ErrRouterConfigConflict
}
routersByHTTPUser, found := r.indexByDomain[domain]
if !found {
routersByHTTPUser = make(map[string][]*Router)
}
vrs, found := routersByHTTPUser[httpUser]
if !found {
vrs = make([]*Router, 0, 1)
}
vr := &Router{
domain: domain,
location: location,
httpUser: httpUser,
payload: payload,
}
vrs = append(vrs, vr)
slices.SortFunc(vrs, func(a, b *Router) int {
return -cmp.Compare(a.location, b.location)
})
routersByHTTPUser[httpUser] = vrs
r.indexByDomain[domain] = routersByHTTPUser
return nil
}
func (r *Routers) Del(domain, location, httpUser string) {
domain = strings.ToLower(domain)
r.mutex.Lock()
defer r.mutex.Unlock()
routersByHTTPUser, found := r.indexByDomain[domain]
if !found {
return
}
vrs, found := routersByHTTPUser[httpUser]
if !found {
return
}
newVrs := make([]*Router, 0)
for _, vr := range vrs {
if vr.location != location {
newVrs = append(newVrs, vr)
}
}
routersByHTTPUser[httpUser] = newVrs
}
func (r *Routers) Get(host, path, httpUser string) (vr *Router, exist bool) {
host = strings.ToLower(host)
r.mutex.RLock()
defer r.mutex.RUnlock()
routersByHTTPUser, found := r.indexByDomain[host]
if !found {
return
}
vrs, found := routersByHTTPUser[httpUser]
if !found {
return
}
for _, vr = range vrs {
if strings.HasPrefix(path, vr.location) {
return vr, true
}
}
return
}
func (r *Routers) exist(host, path, httpUser string) (route *Router, exist bool) {
routersByHTTPUser, found := r.indexByDomain[host]
if !found {
return
}
routers, found := routersByHTTPUser[httpUser]
if !found {
return
}
for _, route = range routers {
if path == route.location {
return route, true
}
}
return
}