forked from vulcand/vulcand
/
host.go
64 lines (52 loc) · 1.41 KB
/
host.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
// Route the request by hostname
package hostroute
import (
"fmt"
. "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/location"
. "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/request"
. "github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/mailgun/vulcan/route"
"strings"
"sync"
)
// This router composer helps to match request by host header and uses inner
// routes to do further matching
type HostRouter struct {
routers map[string]Router
mutex *sync.Mutex
}
func NewHostRouter() *HostRouter {
return &HostRouter{
mutex: &sync.Mutex{},
routers: make(map[string]Router),
}
}
func (h *HostRouter) Route(req Request) (Location, error) {
h.mutex.Lock()
defer h.mutex.Unlock()
hostname := strings.Split(strings.ToLower(req.GetHttpRequest().Host), ":")[0]
matcher, exists := h.routers[hostname]
if !exists {
return nil, nil
}
return matcher.Route(req)
}
func (h *HostRouter) SetRouter(hostname string, router Router) error {
h.mutex.Lock()
defer h.mutex.Unlock()
if router == nil {
return fmt.Errorf("Router can not be nil")
}
h.routers[hostname] = router
return nil
}
func (h *HostRouter) GetRouter(hostname string) Router {
h.mutex.Lock()
defer h.mutex.Unlock()
router := h.routers[hostname]
return router
}
func (h *HostRouter) RemoveRouter(hostname string) {
h.mutex.Lock()
defer h.mutex.Unlock()
delete(h.routers, hostname)
}