frp/pkg/util/vhost/router.go

120 lines
2.0 KiB
Go
Raw Normal View History

package vhost
import (
2019-07-30 16:41:58 +00:00
"errors"
"sort"
"strings"
"sync"
)
2019-07-30 16:41:58 +00:00
var (
ErrRouterConfigConflict = errors.New("router config conflict")
)
2020-05-24 09:48:37 +00:00
type Routers struct {
RouterByDomain map[string][]*Router
mutex sync.RWMutex
}
2020-05-24 09:48:37 +00:00
type Router struct {
domain string
location string
2017-12-12 19:27:43 +00:00
payload interface{}
}
2020-05-24 09:48:37 +00:00
func NewRouters() *Routers {
return &Routers{
RouterByDomain: make(map[string][]*Router),
}
}
2020-05-24 09:48:37 +00:00
func (r *Routers) Add(domain, location string, payload interface{}) error {
r.mutex.Lock()
defer r.mutex.Unlock()
2019-07-30 16:41:58 +00:00
if _, exist := r.exist(domain, location); exist {
return ErrRouterConfigConflict
}
vrs, found := r.RouterByDomain[domain]
if !found {
2020-05-24 09:48:37 +00:00
vrs = make([]*Router, 0, 1)
}
2020-05-24 09:48:37 +00:00
vr := &Router{
2016-12-24 17:53:23 +00:00
domain: domain,
location: location,
2017-12-12 19:27:43 +00:00
payload: payload,
}
2016-12-24 17:53:23 +00:00
vrs = append(vrs, vr)
sort.Sort(sort.Reverse(ByLocation(vrs)))
r.RouterByDomain[domain] = vrs
2019-07-30 16:41:58 +00:00
return nil
}
2020-05-24 09:48:37 +00:00
func (r *Routers) Del(domain, location string) {
r.mutex.Lock()
defer r.mutex.Unlock()
vrs, found := r.RouterByDomain[domain]
if !found {
return
}
2020-05-24 09:48:37 +00:00
newVrs := make([]*Router, 0)
for _, vr := range vrs {
if vr.location != location {
newVrs = append(newVrs, vr)
}
}
r.RouterByDomain[domain] = newVrs
}
2020-05-24 09:48:37 +00:00
func (r *Routers) Get(host, path string) (vr *Router, exist bool) {
r.mutex.RLock()
defer r.mutex.RUnlock()
2016-12-24 17:53:23 +00:00
vrs, found := r.RouterByDomain[host]
if !found {
return
}
// can't support load balance, will to do
for _, vr = range vrs {
2016-12-24 17:53:23 +00:00
if strings.HasPrefix(path, vr.location) {
return vr, true
}
}
return
}
2016-12-24 17:53:23 +00:00
2020-05-24 09:48:37 +00:00
func (r *Routers) exist(host, path string) (vr *Router, exist bool) {
vrs, found := r.RouterByDomain[host]
if !found {
return
}
for _, vr = range vrs {
if path == vr.location {
return vr, true
}
}
return
}
// sort by location
2020-05-24 09:48:37 +00:00
type ByLocation []*Router
2016-12-24 17:53:23 +00:00
func (a ByLocation) Len() int {
return len(a)
}
func (a ByLocation) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByLocation) Less(i, j int) bool {
return strings.Compare(a[i].location, a[j].location) < 0
}