local schema = {
type = "object",
properties = {
i = {type = "number", minimum = 0},
s = {type = "string"},
t = {type = "array", minItems = 1},
ip = {type = "string"},
port = {type = "integer"},
},
required = {"i"},
}
这个 schema 定义了一个非负数 i,字符串 s,非空数组 t,和 ip 跟 port。只有 i 是必需的。
同时,需要实现 check_schema(conf) 方法,完成配置参数的合法性校验。
function _M.check_schema(conf)
return core.schema.check(schema, conf)
end
注:项目已经提供了 core.schema.check 公共方法,直接使用即可完成配置参数校验。
另外,如果插件需要使用一些元数据,可以定义插件的 metadata_schema ,然后就可以通过 Admin API 动态的管理这些元数据了。如:
local metadata_schema = {
type = "object",
properties = {
ikey = {type = "number", minimum = 0},
skey = {type = "string"},
},
required = {"ikey", "skey"},
}
local plugin_name = "example-plugin"
local _M = {
version = 0.1,
priority = 0, -- TODO: add a type field, may be a good idea
name = plugin_name,
schema = schema,
metadata_schema = metadata_schema,
}
你可能之前见过 key-auth 这个插件在它的模块定义时设置了 type = 'auth'。 当一个插件设置 type = 'auth',说明它是个认证插件。
-- key-auth
function _M.check_schema(conf, schema_type)
if schema_type == core.schema.TYPE_CONSUMER then
return core.schema.check(consumer_schema, conf)
else
return core.schema.check(schema, conf)
end
end
-- example-plugin
function _M.check_schema(conf, schema_type)
return core.schema.check(schema, conf)
end
function _M.access(conf, ctx)
core.log.warn(core.json.encode(ctx, true))
......
end
注册公共接口#
插件可以注册暴露给公网的接口。以 jwt-auth 插件为例,这个插件为了让客户端能够签名,注册了 GET /apisix/plugin/jwt/sign 这个接口:
local function gen_token()
-- ...
end
function _M.api()
return {
{
methods = {"GET"},
uri = "/apisix/plugin/jwt/sign",
handler = gen_token,
}
}
end
注意,注册的接口将不会默认暴露,需要使用public-api 插件来暴露它。
注册控制接口#
如果你只想暴露 API 到 localhost 或内网,你可以通过 Control API 来暴露它。
Take a look at example-plugin plugin:
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
如果你没有改过默认的 control API 配置,这个插件暴露的 GET /v1/plugin/example-plugin/hello API 只有通过 127.0.0.1 才能访问它。通过以下命令进行测试:
curl -i -X GET "http://127.0.0.1:9090/v1/plugin/example-plugin/hello"
local core = require "apisix.core"
core.ctx.register_var("a6_labels_zone", function(ctx)
local route = ctx.matched_route and ctx.matched_route.value
if route and route.labels then
return route.labels.zone
end
return nil
end)
=== TEST 1: sanity
--- config
location /t {
content_by_lua_block {
local plugin = require("apisix.plugins.key-auth")
local ok, err = plugin.check_schema({key = 'test-key'}, core.schema.TYPE_CONSUMER)
if not ok then
ngx.say(err)
end
ngx.say("done")
}
}
--- request
GET /t
--- response_body
done
--- no_error_log
[error]