-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathrouting.go
48 lines (40 loc) · 924 Bytes
/
routing.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
package util
import (
"net/url"
"regexp"
"sync"
)
var patCache = map[string]regexp.Regexp{}
var cacheLock = sync.RWMutex{}
func MatchRoutePat(re regexp.Regexp, path string) (map[string]string, bool) {
match := re.FindStringSubmatch(path)
if match == nil {
return nil, false
}
result := map[string]string{}
for i, name := range re.SubexpNames() {
if name != "" {
value, err := url.QueryUnescape(match[i])
if err != nil {
// todo: should this be responding with a 400?
result[name] = match[i]
} else {
result[name] = value
}
}
}
return result, true
}
func getPattern(pat string) regexp.Regexp {
// this implementation is fine since we don't ever delete items from cache.
cacheLock.RLock()
re, isCacheHit := patCache[pat]
cacheLock.RUnlock()
if !isCacheHit {
cacheLock.Lock()
defer cacheLock.Unlock()
re = *regexp.MustCompile(pat)
patCache[pat] = re
}
return re
}