-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing-multidomain.go
99 lines (86 loc) · 1.98 KB
/
routing-multidomain.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
package mvp
import (
"fmt"
"net/http"
"sort"
"strings"
)
type Site struct {
id string
}
func NewSite(id string) *Site {
return &Site{id}
}
var (
NoSite = NewSite("none")
DefaultSite = NewSite("default")
)
type DomainRouter struct {
exact map[string]any
wildcards map[domainWildcard]any
wildcard any
}
func (router *DomainRouter) ValidDomains() []string {
var result []string
for e := range router.exact {
result = append(result, e)
}
for w := range router.wildcards {
result = append(result, w.String())
}
if router.wildcard != nil {
result = append(result, "*")
}
sort.Strings(result)
return result
}
func (router *DomainRouter) Handler(domain string, h http.Handler) {
router.set(domain, h)
}
func (router *DomainRouter) HandleFunc(domain string, h func(http.ResponseWriter, *http.Request)) {
router.Handler(domain, http.HandlerFunc(h))
}
func (router *DomainRouter) Site(domain string, site *Site) {
router.set(domain, site)
}
func (router *DomainRouter) find(domain string) any {
if d := router.exact[domain]; d != nil {
return d
}
n := len(domain)
for w, d := range router.wildcards {
if n >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(domain, w.prefix) && strings.HasSuffix(domain, w.suffix) {
return d
}
}
return router.wildcard
}
func (router *DomainRouter) set(domain string, v any) {
if domain == "" {
return
}
if domain == "*" {
router.wildcard = v
} else if prefix, suffix, found := strings.Cut(domain, "*"); found {
if strings.Count(domain, "*") != 1 {
panic(fmt.Errorf("domain cannot have more than one *: %q", domain))
}
w := domainWildcard{prefix, suffix}
if router.wildcards == nil {
router.wildcards = make(map[domainWildcard]any)
}
router.wildcards[w] = v
} else {
if router.exact == nil {
router.exact = make(map[string]any)
}
router.exact[domain] = v
}
}
type domainWildcard struct {
prefix string
suffix string
}
func (w domainWildcard) String() string {
return w.prefix + "*" + w.suffix
}