-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule_http.go
68 lines (57 loc) · 1.55 KB
/
rule_http.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
package rproxy
import (
"fmt"
"sync"
)
// HTTPRule defines the rule structure
type HTTPRule struct {
URIPrefix, ForwardDst string
}
// HTTPRuleMgr ...
type HTTPRuleMgr struct {
sync.Map
}
// HTTP global rule manager ...
var HTTP *HTTPRuleMgr
func init() {
HTTP = &HTTPRuleMgr{}
}
// CreateOrUpdateRule creates or update rule for uri prefix
// uriPrefix is like /path
// forwardDst is the full access address the request will be forward to
func (h *HTTPRuleMgr) CreateOrUpdateRule(uriPrefix, forwardDst string) {
h.Store(uriPrefix, forwardDst)
}
// RemoveRule removes rule for prefix
func (h *HTTPRuleMgr) RemoveRule(uriPrefix string) error {
if _, ok := h.Load(uriPrefix); ok {
h.Delete(ok)
return nil
}
return fmt.Errorf("unknown uri prefix: " + uriPrefix)
}
// ClearRules removes all rules
func (h *HTTPRuleMgr) ClearRules() {
h.Map = sync.Map{}
}
// ListRules lists all rules
func (h *HTTPRuleMgr) ListRules() []HTTPRule {
rules := []HTTPRule{}
h.Range(func(k, v interface{}) bool {
rule := HTTPRule{URIPrefix: k.(string), ForwardDst: v.(string)}
rules = append(rules, rule)
return true
})
return rules
}
func (h *HTTPRuleMgr) getRule(uriPrefix string) (forwardDst string, err error) {
if v, ok := h.Load(uriPrefix); ok {
return v.(string), nil
}
return forwardDst, fmt.Errorf("unknown uri prefix: " + uriPrefix)
}
func (h *HTTPRuleMgr) rangeRule(f func(uriPrefix, forwardDst string) bool) {
h.Range(func(k, v interface{}) bool {
return f(k.(string), v.(string))
})
}