forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw_example_test.go
49 lines (38 loc) · 1.33 KB
/
mw_example_test.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
package main
import (
"errors"
"net/http"
"github.com/mitchellh/mapstructure"
)
// It's very easy to create custom middleware
// TODO: Write the docs around this
// modifiedMiddleware is a sample custom middleware component, must inherit TykMiddleware
// so you have access to spec and definition data
type modifiedMiddleware struct {
BaseMiddleware
}
type modifiedMiddlewareConfig struct {
CustomData string `mapstructure:"custom_data" json:"custom_data"`
}
func (m *modifiedMiddleware) Name() string {
return "modifiedMiddleware"
}
// Init lets you do any initialisations for the object can be done here
func (m *modifiedMiddleware) Init() {}
// Config retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (m *modifiedMiddleware) Config() (interface{}, error) {
var conf modifiedMiddlewareConfig
err := mapstructure.Decode(m.Spec.ConfigData, &conf)
if err != nil {
return nil, err
}
return conf, nil
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (m *modifiedMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, conf interface{}) (error, int) {
mconf := conf.(modifiedMiddlewareConfig)
if mconf.CustomData == "error" {
return errors.New("Forced error called"), 400
}
return nil, 200
}