The Groovy policy lets the user (ie. API publisher) to run groovy scripts during all the stages of the request processing through the gateway.
The following groovy script is an example executed during the OnResponse phase to change HTTP headers:
response.headers.remove 'X-Powered-By'
response.headers.'X-Gravitee-Gateway-Version' = '0.14.0'
You can attach a groovy script to all phases of the request processing.
Some variables are automatically bind to the Groovy script to let user to use them and define the policy behavior.
Name | Description |
---|---|
request |
Inbound HTTP request |
response |
Outbound HTTP response |
context |
|
result |
Result of the groovy script |
You can also break request or response processing by setting the result to FAILURE
and by providing an HTTP status
code and a message (not mandatory, status is equals to 500 (internal server error) by default).
if (request.headers.containsKey('X-Gravitee-Break')) {
result.state = FAILURE
result.code = 500
result.error = 'Stop request processing due to X-Gravitee-Break header'
} else {
request.headers.'X-Groovy-Policy' = 'ok'
}
You can transform response body content by using a groovy script during the OnResponseContent phase.
Following is an example to show you how to use Groovy policy to transform a JSON content:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def jsonSlurper = new JsonSlurper()
def content = jsonSlurper.parseText(response)
content[0].firstname = 'Hacked ' + content[0].firstname
content[0].country = 'US'
return JsonOutput.toJson(content)