-
Notifications
You must be signed in to change notification settings - Fork 5
/
ctx_dirty_headers.go
71 lines (62 loc) · 2 KB
/
ctx_dirty_headers.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
// Package gobis Mark header as dirty to not forward those headers in the upstream url
// Useful for middleware when they ask for authorization header fox example
package gobis
import (
log "github.com/sirupsen/logrus"
"net/http"
"strings"
)
const (
dirtyHeadersKey GobisContextKey = iota
)
type GobisContextKey int
// DirtHeader Mark a http header as dirty
// Useful to prevent some headers added and used by middleware to not be sent to upstream
// if oldValue is not empty it will make proxy rewrite header with this value
func DirtHeader(req *http.Request, header string, _ ...string) {
var dirtyHeaders = make(map[string]string)
header = sanitizeHeaderName(header)
oldVal := ""
dirtyHeadersPtr := DirtyHeaders(req)
if dirtyHeadersPtr == nil {
dirtyHeaders[header] = oldVal
AddContextValue(req, dirtyHeadersKey, &dirtyHeaders)
return
}
dirtyHeaders = *dirtyHeadersPtr
dirtyHeaders[header] = oldVal
*dirtyHeadersPtr = dirtyHeaders
}
// IsDirtyHeader Return true if a http header is marked as dirty
func IsDirtyHeader(req *http.Request, header string) bool {
header = sanitizeHeaderName(header)
dirtyHeadersPtr := DirtyHeaders(req)
if dirtyHeadersPtr == nil {
return false
}
dirtyHeaders := *dirtyHeadersPtr
_, ok := dirtyHeaders[header]
return ok
}
// UndirtHeader Remove a http header from the list of dirty header
func UndirtHeader(req *http.Request, header string) {
header = sanitizeHeaderName(header)
dirtyHeadersPtr := DirtyHeaders(req)
if dirtyHeadersPtr == nil {
return
}
dirtyHeaders := *dirtyHeadersPtr
delete(dirtyHeaders, header)
*dirtyHeadersPtr = dirtyHeaders
}
// DirtyHeaders Retrieve all http headers marked as dirty
func DirtyHeaders(req *http.Request) *map[string]string {
var dirtyHeaders *map[string]string
if err := InjectContextValue(req, dirtyHeadersKey, &dirtyHeaders); err != nil {
log.Errorf("got error when getting DirtyHeaders value: %s", err)
}
return dirtyHeaders
}
func sanitizeHeaderName(header string) string {
return strings.ToLower(strings.TrimSpace(header))
}