作用
apisix的control api 可以給插件暴露出插件的api。也就是通過調(diào)用api 就能執(zhí)行插件中預(yù)先設(shè)置的邏輯。api可以用于控制插件行為御铃,比如通過control api 使用POST 方式修改插件中部分參數(shù)酬荞。api 也可以獲取插件當(dāng)前運(yùn)行過程中的信息,比如使用GET方式獲取插件當(dāng)前設(shè)置的參數(shù)或者某個(gè)安全插件當(dāng)前攔截的請(qǐng)求數(shù)粟瞬。
開發(fā)方法
只需要在插件的代碼中實(shí)現(xiàn)control_api 方法同仆。其中各字段作用如下:
methods: 該control api 支持的http 方法。
uris:control api http 請(qǐng)求的地址
handler:control api 的具體處理方法的函數(shù)名裙品。example-plugin中對(duì)應(yīng)的hello()方法就是對(duì)應(yīng)的處理邏輯俗批。
local function hello()
local args = ngx.req.get_uri_args()
if args["json"] then
return 200, {msg = "world"}
else
return 200, "world\n"
end
end
function _M.control_api()
return {
{
methods = {"GET"},
uris = {"/v1/plugin/example-plugin/hello"},
handler = hello,
}
}
end
api調(diào)用方法
api 訪問的端口默認(rèn)是9090,可以進(jìn)行自定義修改市怎。如果不進(jìn)行修改上例中的請(qǐng)求地址就是:
curl -i -X GET "http://127.0.0.1:9090/v1/plugin/example-plugin/hello"
insert-header使用control api示例
在上節(jié)的insert-header 自定義插件的基礎(chǔ)上通過control api 實(shí)現(xiàn)獲取請(qǐng)求次數(shù)岁忘,代碼實(shí)現(xiàn)如下:
local function get_request_count()
return 200, tostring(request_count)
end
function _M.control_api()
return {
{
methods = {"GET"},
uris = {"/v1/plugin/insert-header/request_count"},
handler = get_request_count,
}
}
end
完整插件代碼如下:
local ngx = ngx
local core = require("apisix.core")
local request_count = 0
local schema = {
type = "object",
properties = {
header_name = { type = "string", default = "test_header" },
header_value = { type = "string" }
},
required = { "header_value" }
}
local _M = {
version = 0.1,
priority = 30,
name = "insert-header",
schema = schema
}
function _M.check_schema(conf, schema_type)
return core.schema.check(schema, conf)
end
function _M.access(conf, ctx)
-- 添加header頭
ngx.req.set_header(conf.header_name, conf.header_value)
request_count = request_count + 1
end
return _M
local function get_request_count()
return 200, tostring(request_count)
end
function _M.control_api()
return {
{
methods = {"GET"},
uris = {"/v1/plugin/insert-header/request_count"},
handler = get_request_count,
}
}
end