问题
之前要在kong上注册一些API,在处理到拥有path参数的接口时有点犯难了,通过官方文档查询kong支持的插件,发现可以使用request-transformer
插件配合正则来重写请求路径,从而可以达到处理path参数的需求。
request-transformer
简单看一下官方对于这个插件的介绍:
The Request Transformer plugin for Kong allows simple transformation of requests before they reach the upstream server. These transformations can be simple substitutions or complex ones matching portions of incoming requests using regular expressions, saving those matched strings into variables, and substituting those strings into transformed requests using flexible templates.
简单翻译过来就是该插件可以对请求路径做一些替换,用正则将请求中的部分参数作为字符串存入到某个变量中,随后可以对它进行替换。详细的说明可以查看官方文档,我这里简单说明一下如何用它处理path参数。
使用
在kong上去给api创建一个带有path参数的route:
curl -i -X POST \
--url http://localhost:8001/services/test-service/routes \
--data 'hosts[]=127.0.0.1' \
--data 'paths[]=/getProducts/(?<id>)\S+)/test$'\
--data 'methods[]=GET'
原始的path应该是/getProducts/{id}/test
,在创建route的时候需要将这里的id
使用正则匹配,并用变量id
接收,并在path的最后面加上$
符号,不管path里有多少参数,都在最后加上$
符号!!
创建完route之后,就需要给route添加request-transformer
插件:
curl -i -X POST \
--url http://localhost:8001/routes/{你刚刚创建出来的route}/plugins \
--data "name=request-transformer"
--data "config.replace.uri=/getProducts/$(uri_captures[1])/test"
如果不止一个path参数,那么就在对应的地方加上$(uri_captures[2])
,$(uri_captures[3])
、、、