-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_header.go
78 lines (68 loc) · 1.5 KB
/
add_header.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
package main
import (
"errors"
"net/http"
"regexp"
"strings"
)
type modHeaderOption struct {
re *regexp.Regexp
includeHost bool
name string
value string
}
type ModifyHeaderHandler struct {
NextHandler http.Handler
options []modHeaderOption
}
func (h *ModifyHeaderHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
next := h.NextHandler
if next == nil {
next = http.DefaultServeMux
}
for _, opt := range h.options {
testString := req.URL.Path
if opt.includeHost {
testString = req.Host + testString
}
if opt.re.MatchString(testString) {
value, solved, err := GetRequestParam(opt.value, req)
if err != nil {
logf(req, logLevelError, "cannot solve parameter: %#v: %s", opt.value, err)
}
if solved {
w.Header().Add(opt.name, value)
}
}
}
next.ServeHTTP(w, req)
}
func (h *ModifyHeaderHandler) ParseAddHdr(opt string) error {
includeHost := false
if strings.HasPrefix(opt, "*") {
includeHost = true
opt = opt[1:]
}
eqIdx := strings.Index(opt, "=")
if eqIdx < 0 {
return errors.New("no '=' in option")
}
re, err := regexp.Compile(opt[:eqIdx])
if err != nil {
return err
}
opt = opt[eqIdx+1:]
var headerValue string
nameIdx := strings.Index(opt, ":")
if nameIdx < 0 {
return errors.New("no ':' in option value")
}
headerValue = opt[nameIdx+1:]
h.options = append(h.options, modHeaderOption{
re: re,
includeHost: includeHost,
name: opt[:nameIdx],
value: headerValue,
})
return nil
}