forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
res_handler_header_transform.go
84 lines (73 loc) · 2.12 KB
/
res_handler_header_transform.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
package main
import (
"github.com/mitchellh/mapstructure"
"net/http"
"net/url"
"strings"
)
type RevProxyTransform struct {
Headers []string // List of HTTP headers to be modified
Target_host string // Target host for reverse proxy
}
type HeaderTransformOptions struct {
RevProxyTransform RevProxyTransform `mapstructure:"rev_proxy_header_cleanup" \
bson:"rev_proxy_header_cleanup" \
json:"rev_proxy_header_cleanup"`
}
type HeaderTransform struct {
Spec *APISpec
config HeaderTransformOptions
}
func (h HeaderTransform) New(c interface{}, spec *APISpec) (TykResponseHandler, error) {
thisHandler := HeaderTransform{}
thisModuleConfig := HeaderTransformOptions{}
err := mapstructure.Decode(c, &thisModuleConfig)
if err != nil {
log.Error(err)
return nil, err
}
thisHandler.config = thisModuleConfig
thisHandler.Spec = spec
return thisHandler, nil
}
func (h HeaderTransform) HandleResponse(rw http.ResponseWriter,
res *http.Response, req *http.Request, ses *SessionState) error {
// Parse target_host parameter from configuration
target_url, err := url.Parse(h.config.RevProxyTransform.Target_host)
if err != nil {
log.Error(err)
return err
}
for _, v := range h.config.RevProxyTransform.Headers {
// check if header is present and its value is not empty
if len(res.Header[v]) == 0 || len(res.Header[v][0]) == 0 {
continue
}
// Replace scheme
NewHeaderValue := strings.Replace(
res.Header[v][0], h.Spec.target.Scheme, target_url.Scheme, -1)
// Replace host
NewHeaderValue = strings.Replace(
NewHeaderValue, h.Spec.target.Host, target_url.Host, -1)
// Transform path
if h.Spec.Proxy.StripListenPath {
if len(h.Spec.target.Path) != 0 {
NewHeaderValue = strings.Replace(
NewHeaderValue, h.Spec.target.Path,
h.Spec.Proxy.ListenPath, -1)
} else {
NewHeaderValue = strings.Replace(
NewHeaderValue, req.URL.Path,
h.Spec.Proxy.ListenPath+req.URL.Path, -1)
}
} else {
if len(h.Spec.target.Path) != 0 {
NewHeaderValue = strings.Replace(
NewHeaderValue, h.Spec.target.Path,
"/", -1)
}
}
res.Header[v][0] = NewHeaderValue
}
return nil
}