forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres_handler_transform.go
104 lines (85 loc) · 2.47 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
package main
import (
"bytes"
"encoding/json"
"github.com/lonelycode/tykcommon"
"github.com/mitchellh/mapstructure"
//"io"
"io/ioutil"
"net/http"
//"time"
"strconv"
)
type ResponsetransformOptions struct {
//FlushInterval time.Duration
}
type ResponseTransformMiddleware struct {
Spec *APISpec
config ResponsetransformOptions
}
func (rt ResponseTransformMiddleware) New(c interface{}, spec *APISpec) (TykResponseHandler, error) {
thisHandler := ResponseTransformMiddleware{}
thisModuleConfig := ResponsetransformOptions{}
err := mapstructure.Decode(c, &thisModuleConfig)
if err != nil {
log.Error(err)
return nil, err
}
thisHandler.config = thisModuleConfig
thisHandler.Spec = spec
log.Warning("Response body transform processor initialised")
return thisHandler, nil
}
// func (rt ResponseTransformMiddleware) copyResponse(dst io.Writer, src io.Reader) {
// if rt.FlushInterval != 0 {
// if wf, ok := dst.(writeFlusher); ok {
// mlw := &maxLatencyWriter{
// dst: wf,
// latency: p.FlushInterval,
// done: make(chan bool),
// }
// go mlw.flushLoop()
// defer mlw.stop()
// dst = mlw
// }
// }
// io.Copy(dst, src)
// }
func (rt ResponseTransformMiddleware) HandleResponse(rw http.ResponseWriter, res *http.Response, req *http.Request, ses *SessionState) error {
// New request checker, more targetted, less likely to fail
var stat RequestStatus
var meta interface{}
var found bool
_, versionPaths, _, _ := rt.Spec.GetVersionData(req)
found, meta = rt.Spec.CheckSpecMatchesStatus(req.URL.Path, req.Method, versionPaths, TransformedResponse)
if found {
stat = StatusTransformResponse
}
if stat == StatusTransformResponse {
thisMeta := meta.(*TransformSpec)
// Read the body:
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
// Put into an interface:
var bodyData interface{}
switch thisMeta.TemplateMeta.TemplateData.Input {
case tykcommon.RequestXML:
log.Warning("XML Input is not supprted")
case tykcommon.RequestJSON:
json.Unmarshal(body, &bodyData)
default:
json.Unmarshal(body, &bodyData)
}
// Apply to template
var bodyBuffer bytes.Buffer
log.Warning("RUNNING TRANSFORM")
err = thisMeta.Template.Execute(&bodyBuffer, bodyData)
if err != nil {
log.Error("Failed to apply template to request: ", err)
}
res.ContentLength = int64(bodyBuffer.Len())
res.Header.Set("Content-Length", strconv.Itoa(bodyBuffer.Len()))
res.Body = ioutil.NopCloser(&bodyBuffer)
}
return nil
}