-
Notifications
You must be signed in to change notification settings - Fork 0
/
res_handler_transform.go
161 lines (132 loc) · 3.57 KB
/
res_handler_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package main
import (
"bytes"
"compress/flate"
"compress/gzip"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strconv"
"github.com/Sirupsen/logrus"
"github.com/clbanning/mxj"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/user"
)
type ResponseTransformMiddleware struct {
Spec *APISpec
}
func (h *ResponseTransformMiddleware) Init(c interface{}, spec *APISpec) error {
h.Spec = spec
return nil
}
func respBodyReader(req *http.Request, resp *http.Response) io.ReadCloser {
if req.Header.Get("Accept-Encoding") == "" {
return resp.Body
}
switch resp.Header.Get("Content-Encoding") {
case "gzip":
reader, err := gzip.NewReader(resp.Body)
if err != nil {
log.Error("Body decompression error:", err)
return ioutil.NopCloser(bytes.NewReader(nil))
}
// represents unknown length
resp.ContentLength = 0
return reader
case "deflate":
// represents unknown length
resp.ContentLength = 0
return flate.NewReader(resp.Body)
}
return resp.Body
}
func compressBuffer(in bytes.Buffer, encoding string) (out bytes.Buffer) {
switch encoding {
case "gzip":
zw := gzip.NewWriter(&out)
zw.Write(in.Bytes())
zw.Close()
case "deflate":
zw, _ := flate.NewWriter(&out, 1)
zw.Write(in.Bytes())
zw.Close()
default:
out = in
}
return out
}
func (h *ResponseTransformMiddleware) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *user.SessionState) error {
logger := log.WithFields(logrus.Fields{
"prefix": "outbound-transform",
"server_name": h.Spec.Proxy.TargetURL,
"api_id": h.Spec.APIID,
"path": req.URL.Path,
})
_, versionPaths, _, _ := h.Spec.Version(req)
found, meta := h.Spec.CheckSpecMatchesStatus(req, versionPaths, TransformedResponse)
if !found {
return nil
}
tmeta := meta.(*TransformSpec)
respBody := respBodyReader(req, res)
body, _ := ioutil.ReadAll(respBody)
defer respBody.Close()
// Put into an interface:
bodyData := make(map[string]interface{})
switch tmeta.TemplateData.Input {
case apidef.RequestXML:
if len(body) == 0 {
body = []byte("<_/>")
}
mxj.XmlCharsetReader = WrappedCharsetReader
var err error
xmlMap, err := mxj.NewMapXml(body) // unmarshal
if err != nil {
logger.WithError(err).Error("Error unmarshalling XML")
//todo return error
break
}
for k, v := range xmlMap {
bodyData[k] = v
}
default: // apidef.RequestJSON
if len(body) == 0 {
body = []byte("{}")
}
var tempBody interface{}
if err := json.Unmarshal(body, &tempBody); err != nil {
logger.WithError(err).Error("Error unmarshalling JSON")
//todo return error
break
}
switch tempBody.(type) {
case []interface{}:
bodyData["array"] = tempBody
case map[string]interface{}:
bodyData = tempBody.(map[string]interface{})
}
}
if h.Spec.EnableContextVars {
bodyData["_tyk_context"] = ctxGetData(req)
}
if tmeta.TemplateData.EnableSession {
if session := ctxGetSession(req); session != nil {
bodyData["_tyk_meta"] = session.MetaData
} else {
logger.Error("Session context was enabled but not found.")
}
}
// Apply to template
var bodyBuffer bytes.Buffer
if err := tmeta.Template.Execute(&bodyBuffer, bodyData); err != nil {
logger.WithError(err).Error("Failed to apply template to request")
}
// Re-compress if original upstream response was compressed
encoding := res.Header.Get("Content-Encoding")
bodyBuffer = compressBuffer(bodyBuffer, encoding)
res.ContentLength = int64(bodyBuffer.Len())
res.Header.Set("Content-Length", strconv.Itoa(bodyBuffer.Len()))
res.Body = ioutil.NopCloser(&bodyBuffer)
return nil
}