apisix control api的使用
2023-02-26 09:51:49 时间
作用
apisix的control api 可以给插件暴露出插件的api。也就是通过调用api 就能执行插件中预先设置的逻辑。api可以用于控制插件行为,比如通过control api 使用POST 方式修改插件中部分参数。api 也可以获取插件当前运行过程中的信息,比如使用GET方式获取插件当前设置的参数或者某个安全插件当前拦截的请求数。
开发方法
只需要在插件的代码中实现control_api 方法。其中各字段作用如下: methods: 该control api 支持的http 方法。 uris:control api http 请求的地址 handler:control api 的具体处理方法的函数名。example-plugin中对应的hello()方法就是对应的处理逻辑。
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调用方法
api 访问的端口默认是9090,可以进行自定义修改。如果不进行修改上例中的请求地址就是: curl -i -X GET "http://127.0.0.1:9090/v1/plugin/example-plugin/hello"
insert-header使用control api示例
在上节的insert-header 自定义插件的基础上通过control api 实现获取请求次数,代码实现如下:
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
相关文章
- 基于Python的人脸识别考勤监控
- Python答题游戏
- Python调用百度API实现图像识别
- Python全栈疫情分析项目
- Python-基础-if语句快速入门
- Python-基础-循环语句快速入门
- Python-GUI签名
- 【2】VScode 搭建python和tensorflow环境
- python 简易时钟
- 【1】windows系统如何安装后缀是whl的python库
- 【2】超级详细Python-matplotlib画图,手把手教你画图!(线条颜色、大小、线形、标签)
- 【4】python读写文件操作---详细讲解!
- 【2】Anaconda下:ipython文件的打开方式,Jupyter Notebook中运行.py文件,快速打开ipython文件的方法!
- 【编写环境一】遇到常见python函数处理方式
- 【编写环境二】python库scipy.stats各种分布函数生成、以及随机数生成【泊松分布、正态分布等】
- Python xlwt数据保存到 Excel中以及xlrd读取excel文件画图
- 强化学习技巧三:Python多进程
- 强化学习技巧五:numba提速python程序
- 【7】python_matplotlib 输出(保存)矢量图方法;画图时图例说明(legend)放到图像外侧;Python_matplotlib图例放在外侧保存时显示不完整问题解决
- 【8】python_matplotlib改变横坐标和纵坐标上的刻度(ticks)、sagemath-list_plot()调整图例(legend)中点的数量、Matplotlib画各种论文图