Skip to content

Instantly share code, notes, and snippets.

@asolera
Created May 31, 2021 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asolera/601467bc1ce110b952c60451f5fdcd7b to your computer and use it in GitHub Desktop.
Save asolera/601467bc1ce110b952c60451f5fdcd7b to your computer and use it in GitHub Desktop.
WSO2 Conditional Redirecting Mediation Policy

This mediation policy redirects requests based on resource variable, but keeping limit and offset query params (ignore rest).

"Endpoint type" MUST be set to "Dynamic Endpoint" at "Implement" publisher tab.

<sequence name="ConditionalRedirectExample" statistics="enable" trace="enable" xmlns="http://ws.apache.org/ns/synapse">
<!-- URL example: https://apim-example/context/v1/2021?foo=bar&limit=10&offset=20 -->
<!-- Process first query param (limit) -->
<switch source="boolean($url:limit)">
<case regex="true">
<property name="param_limit" expression="$url:limit"/>
</case>
<default>
<property name="param_limit" value="100"/>
</default>
</switch>
<!-- Process second query param (offset) -->
<switch source="boolean($url:offset)">
<case regex="true">
<property name="param_offset" expression="$url:offset"/>
</case>
<default>
<property name="param_offset" value="0"/>
</default>
</switch>
<!-- Set backend endpoint based on variable "year" (MUST be named year in publisher) -->
<switch source="get-property('uri.var.year')">
<case regex="2021">
<property name="target_url" value="https://endpoint1/"/>
</case>
<default>
<property name="target_url" value="https://endpoint2/"/>
</default>
</switch>
<!-- Remove original path from request -->
<property name="REST_URL_POSTFIX" action="remove" scope="axis2"/>
<!-- Redirect request -->
<header name="To" expression="fn:concat(get-property('target_url'), '?limit=', get-property('param_limit'), '&amp;offset=', get-property('param_offset'))"></header>
<!-- Enable statistics -->
<property expression="get-property('target_url')" name="ENDPOINT_ADDRESS"></property>
</sequence>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment