1
0
Files
envoy-apisix/plugins/plugin.lua
2023-04-14 17:12:13 +08:00

63 lines
1.7 KiB
Lua

local log = require("core.log")
local ctx = require("core.ctx")
local json = require("core.json")
local _M = {version = 0.2}
local phases = {
request = {
'access',
'rewrite'
},
response = {
'header_filter',
'body_filter'
}
}
function _M.run(handle, phase, plugins)
if not plugins or #plugins == 0 then
return ctx
end
local resp_header = {}
local context = {
headers = handle:headers(),
body = handle:body(),
log = log.new(handle),
var = ctx.set_vars_meta(handle),
}
function context.set_resp_header(key, value)
resp_header[key] = value
end
for _, plugin in ipairs(plugins) do
local ok, plugin_object = pcall(require, "plugins." .. plugin.name)
if ok then
local earth_phases = phases[phase]
for _, phase_name in ipairs(earth_phases) do
local phase_func = plugin_object[phase_name]
if type(phase_func) == "function" then
handle:logTrace("phase_name: " .. plugin.name .. "." .. phase_name)
local status, body = phase_func(plugin.conf, context)
if status then
resp_header[":status"] = status
if type(body) == "table" then
body = json.encode(body)
end
return handle:respond(resp_header, body)
end
end
end
else
handle:logWarn("failed to load plugin ["..plugin.name.."] err: "..plugin_object)
end
end
return ctx
end
return _M