-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathplugin.go
275 lines (234 loc) · 7.63 KB
/
plugin.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// SPDX-License-Identifier: Apache-2.0
package proxy
import (
"context"
"fmt"
"io"
"net/url"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/logging"
"github.com/luraproject/lura/v2/proxy/plugin"
)
// NewPluginMiddleware returns an endpoint middleware wrapped (if required) with the plugin middleware.
// The plugin middleware will try to load all the required plugins from the register and execute them in order.
// RequestModifiers are executed before passing the request to the next middlware. ResponseModifiers are executed
// once the response is returned from the next middleware.
func NewPluginMiddleware(logger logging.Logger, endpoint *config.EndpointConfig) Middleware {
cfg, ok := endpoint.ExtraConfig[plugin.Namespace].(map[string]interface{})
if !ok {
return emptyMiddlewareFallback(logger)
}
return newPluginMiddleware(logger, "ENDPOINT", endpoint.Endpoint, cfg)
}
// NewBackendPluginMiddleware returns a backend middleware wrapped (if required) with the plugin middleware.
// The plugin middleware will try to load all the required plugins from the register and execute them in order.
// RequestModifiers are executed before passing the request to the next middlware. ResponseModifiers are executed
// once the response is returned from the next middleware.
func NewBackendPluginMiddleware(logger logging.Logger, remote *config.Backend) Middleware {
cfg, ok := remote.ExtraConfig[plugin.Namespace].(map[string]interface{})
if !ok {
return emptyMiddlewareFallback(logger)
}
return newPluginMiddleware(logger, "BACKEND",
fmt.Sprintf("%s %s -> %s", remote.ParentEndpointMethod, remote.ParentEndpoint, remote.URLPattern), cfg)
}
func newPluginMiddleware(logger logging.Logger, tag, pattern string, cfg map[string]interface{}) Middleware {
plugins, ok := cfg["name"].([]interface{})
if !ok {
return emptyMiddlewareFallback(logger)
}
var reqModifiers []func(interface{}) (interface{}, error)
var respModifiers []func(interface{}) (interface{}, error)
for _, p := range plugins {
name, ok := p.(string)
if !ok {
continue
}
if mf, ok := plugin.GetRequestModifier(name); ok {
if fn := mf(cfg); fn != nil {
reqModifiers = append(reqModifiers, fn)
}
continue
}
if mf, ok := plugin.GetResponseModifier(name); ok {
if fn := mf(cfg); fn != nil {
respModifiers = append(respModifiers, fn)
}
}
}
totReqModifiers, totRespModifiers := len(reqModifiers), len(respModifiers)
if totReqModifiers == totRespModifiers && totRespModifiers == 0 {
return emptyMiddlewareFallback(logger)
}
logger.Debug(
fmt.Sprintf(
"[%s: %s][Modifier Plugins] Adding %d request and %d response modifiers",
tag,
pattern,
totReqModifiers,
totRespModifiers,
),
)
return func(next ...Proxy) Proxy {
if len(next) > 1 {
logger.Fatal("too many proxies for this proxy middleware: newPluginMiddleware only accepts 1 proxy, got %d tag: %s, pattern: %s",
len(next), tag, pattern)
return nil
}
if totReqModifiers == 0 {
return func(ctx context.Context, r *Request) (*Response, error) {
resp, err := next[0](ctx, r)
if err != nil {
return resp, err
}
return executeResponseModifiers(ctx, respModifiers, resp, newRequestWrapper(ctx, r))
}
}
if totRespModifiers == 0 {
return func(ctx context.Context, r *Request) (*Response, error) {
var err error
r, err = executeRequestModifiers(ctx, reqModifiers, r)
if err != nil {
return nil, err
}
return next[0](ctx, r)
}
}
return func(ctx context.Context, r *Request) (*Response, error) {
var err error
r, err = executeRequestModifiers(ctx, reqModifiers, r)
if err != nil {
return nil, err
}
resp, err := next[0](ctx, r)
if err != nil {
return resp, err
}
return executeResponseModifiers(ctx, respModifiers, resp, newRequestWrapper(ctx, r))
}
}
}
func executeRequestModifiers(ctx context.Context, reqModifiers []func(interface{}) (interface{}, error), r *Request) (*Request, error) {
var tmp RequestWrapper
tmp = newRequestWrapper(ctx, r)
for _, f := range reqModifiers {
res, err := f(tmp)
if err != nil {
return nil, err
}
t, ok := res.(RequestWrapper)
if !ok {
continue
}
tmp = t
}
r.Method = tmp.Method()
r.URL = tmp.URL()
r.Query = tmp.Query()
r.Path = tmp.Path()
r.Body = tmp.Body()
r.Params = tmp.Params()
r.Headers = tmp.Headers()
return r, nil
}
func executeResponseModifiers(ctx context.Context, respModifiers []func(interface{}) (interface{}, error), r *Response, req RequestWrapper) (*Response, error) {
var tmp ResponseWrapper
tmp = responseWrapper{
ctx: ctx,
request: req,
data: r.Data,
isComplete: r.IsComplete,
metadata: metadataWrapper{
headers: r.Metadata.Headers,
statusCode: r.Metadata.StatusCode,
},
io: r.Io,
}
for _, f := range respModifiers {
res, err := f(tmp)
if err != nil {
return nil, err
}
t, ok := res.(ResponseWrapper)
if !ok {
continue
}
tmp = t
}
r.Data = tmp.Data()
r.IsComplete = tmp.IsComplete()
r.Io = tmp.Io()
r.Metadata = Metadata{}
r.Metadata.Headers = tmp.Headers()
r.Metadata.StatusCode = tmp.StatusCode()
return r, nil
}
// RequestWrapper is an interface for passing proxy request between the lura pipe and the loaded plugins
type RequestWrapper interface {
Params() map[string]string
Headers() map[string][]string
Body() io.ReadCloser
Method() string
URL() *url.URL
Query() url.Values
Path() string
}
// ResponseWrapper is an interface for passing proxy response between the lura pipe and the loaded plugins
type ResponseWrapper interface {
Data() map[string]interface{}
Io() io.Reader
IsComplete() bool
Headers() map[string][]string
StatusCode() int
}
func newRequestWrapper(ctx context.Context, r *Request) *requestWrapper {
return &requestWrapper{
ctx: ctx,
method: r.Method,
url: r.URL,
query: r.Query,
path: r.Path,
body: r.Body,
params: r.Params,
headers: r.Headers,
}
}
type requestWrapper struct {
ctx context.Context
method string
url *url.URL
query url.Values
path string
body io.ReadCloser
params map[string]string
headers map[string][]string
}
func (r *requestWrapper) Context() context.Context { return r.ctx }
func (r *requestWrapper) Method() string { return r.method }
func (r *requestWrapper) URL() *url.URL { return r.url }
func (r *requestWrapper) Query() url.Values { return r.query }
func (r *requestWrapper) Path() string { return r.path }
func (r *requestWrapper) Body() io.ReadCloser { return r.body }
func (r *requestWrapper) Params() map[string]string { return r.params }
func (r *requestWrapper) Headers() map[string][]string { return r.headers }
type metadataWrapper struct {
headers map[string][]string
statusCode int
}
func (m metadataWrapper) Headers() map[string][]string { return m.headers }
func (m metadataWrapper) StatusCode() int { return m.statusCode }
type responseWrapper struct {
ctx context.Context
request interface{}
data map[string]interface{}
isComplete bool
metadata metadataWrapper
io io.Reader
}
func (r responseWrapper) Context() context.Context { return r.ctx }
func (r responseWrapper) Request() interface{} { return r.request }
func (r responseWrapper) Data() map[string]interface{} { return r.data }
func (r responseWrapper) IsComplete() bool { return r.isComplete }
func (r responseWrapper) Io() io.Reader { return r.io }
func (r responseWrapper) Headers() map[string][]string { return r.metadata.headers }
func (r responseWrapper) StatusCode() int { return r.metadata.statusCode }