github.com/Tyktechnologies/tyk@v2.9.5+incompatible/gateway/mw_example_test.go (about) 1 package gateway 2 3 import ( 4 "errors" 5 "net/http" 6 7 "github.com/mitchellh/mapstructure" 8 ) 9 10 // It's very easy to create custom middleware 11 // TODO: Write the docs around this 12 13 // modifiedMiddleware is a sample custom middleware component, must inherit TykMiddleware 14 // so you have access to spec and definition data 15 type modifiedMiddleware struct { 16 BaseMiddleware 17 } 18 19 type modifiedMiddlewareConfig struct { 20 CustomData string `mapstructure:"custom_data" json:"custom_data"` 21 } 22 23 func (m *modifiedMiddleware) Name() string { 24 return "modifiedMiddleware" 25 } 26 27 // Init lets you do any initialisations for the object can be done here 28 func (m *modifiedMiddleware) Init() {} 29 30 // Config retrieves the configuration from the API config - we user mapstructure for this for simplicity 31 func (m *modifiedMiddleware) Config() (interface{}, error) { 32 var conf modifiedMiddlewareConfig 33 34 err := mapstructure.Decode(m.Spec.ConfigData, &conf) 35 if err != nil { 36 return nil, err 37 } 38 39 return conf, nil 40 } 41 42 // ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail 43 func (m *modifiedMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, conf interface{}) (error, int) { 44 mconf := conf.(modifiedMiddlewareConfig) 45 if mconf.CustomData == "error" { 46 return errors.New("Forced error called"), 400 47 } 48 return nil, 200 49 }