zl程序教程

您现在的位置是:首页 >  Python

当前栏目

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