This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
rule.go
73 lines (62 loc) · 2.04 KB
/
rule.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
package filter
import (
"net/http"
"regexp"
)
type rule struct {
path *regexp.Regexp
contentType *regexp.Regexp
pathAndContentTypeCombination pathAndContentTypeCombination
searchPattern *regexp.Regexp
replacement []byte
}
type pathAndContentTypeCombination string
const (
pathAndContentTypeAndCombination = pathAndContentTypeCombination("and")
pathAndContentTypeOrCombination = pathAndContentTypeCombination("or")
)
var possiblePathAndContentTypeCombination = []pathAndContentTypeCombination{
pathAndContentTypeAndCombination,
pathAndContentTypeOrCombination,
}
func (instance rule) evaluatePathAndContentTypeResult(pathMatch bool, contentTypeMatch bool) bool {
combination := instance.pathAndContentTypeCombination
if combination == pathAndContentTypeCombination("") {
combination = pathAndContentTypeAndCombination
}
if combination == pathAndContentTypeAndCombination {
return pathMatch && contentTypeMatch
}
if combination == pathAndContentTypeOrCombination {
return pathMatch || contentTypeMatch
}
return false
}
func (instance *rule) matches(request *http.Request, responseHeader *http.Header) bool {
var pathMatch, contentTypeMatch bool
if instance.path != nil {
pathMatch = request != nil && instance.path.MatchString(request.URL.Path)
} else {
pathMatch = true
}
if instance.contentType != nil {
contentTypeMatch = responseHeader != nil && instance.contentType.MatchString(responseHeader.Get("Content-Type"))
} else {
contentTypeMatch = true
}
return instance.evaluatePathAndContentTypeResult(pathMatch, contentTypeMatch)
}
func (instance *rule) execute(request *http.Request, responseHeader *http.Header, input []byte) []byte {
pattern := instance.searchPattern
if pattern == nil {
return input
}
action := &ruleReplaceAction{
request: request,
responseHeader: responseHeader,
searchPattern: instance.searchPattern,
replacement: instance.replacement,
}
output := pattern.ReplaceAllFunc(input, action.replacer)
return output
}