-
Notifications
You must be signed in to change notification settings - Fork 2
/
common.go
94 lines (79 loc) · 1.69 KB
/
common.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
package server
import (
"bytes"
"context"
"errors"
"github.com/valyala/fasthttp"
"regexp"
)
type KVTuple struct {
K, V string
}
const (
// StandardContextKey use this key to access context.Context from ctx.UserValues
standardContextKey = "_ctx"
DurianName = "durian"
DurianVersion = "0.0.1"
)
type StorageKey int
const (
UpstreamKey StorageKey = iota
ServerNameKey
DocRootKey
)
func GetStdCtx(reqCtx *fasthttp.RequestCtx) context.Context {
ctx, ok := reqCtx.UserValue(standardContextKey).(context.Context)
if ok {
return ctx
}
return context.TODO()
}
type Upstream struct {
Name string
Backends []Backend
}
type Backend struct {
Network string
Addr string
Weight int
Backup bool
}
type location struct {
pattern *regexp.Regexp
prefix []byte
}
func (lo *location) Match(uri []byte) bool {
if lo.pattern != nil {
return lo.pattern.Match(uri)
}
return bytes.HasPrefix(uri, lo.prefix)
}
type LocationMatcher interface {
Match(uri []byte) bool
}
func NewLocationMatcher(firstLine []string) (LocationMatcher, error) {
if len(firstLine) == 0 {
return nil, errors.New("nil firstLine")
}
if len(firstLine) == 1 {
return &location{prefix: []byte(firstLine[0])}, nil
}
re, err := regexp.Compile(firstLine[1])
if err != nil {
return nil, err
}
return &location{pattern: re}, nil
}
type combineMather struct {
should LocationMatcher
exclude LocationMatcher
}
func (c *combineMather) Match(uri []byte) bool {
if c.should.Match(uri) && !c.exclude.Match(uri) {
return true
}
return false
}
func NewCombineMatcher(shouldMatch LocationMatcher, exclude LocationMatcher) LocationMatcher {
return &combineMather{should: shouldMatch, exclude: exclude}
}