kong自定义插件实现——使用post发送请求
程序员文章站
2024-03-21 20:29:10
...
kong插件机制
代码实现
-- handler.lua
local BasePlugin = require "kong.plugins.base_plugin"
-- 调用模块
local zhttp = require "resty.http" #一个resty 包,需要下载到指定目录
local XngAuthHandler = BasePlugin:extend()
local timeout = 5000
local uri = "http://localhost:8500/auth/v1/api/valid"
XngAuthHandler.VERSION = "1.0.0"
XngAuthHandler.PRIORITY = 10 # 优先级
#在转发到你的服务之前,会走这个,所以在这里添加你的逻辑就可以
function XngAuthHandler:access(config)
local httpc = zhttp.new()
httpc:set_timeout(timeout)
local res, err = httpc:request_uri(uri, {
method = "POST",
headers = kong.request.get_headers()#获取请求的所有头部
}
)
httpc:set_keepalive(5000, 100)
httpc:close()
local mid = "0"
if not res then
kong.log.err("res is nil")
else
mid = res.headers["X-Mid"]
if not mid then
mid = "0"
end
end
kong.service.request.set_header("X-Mid", mid)#透传到服务前,添加字段
end
return XngAuthHandler
一些概念参考文档:
https://cloud.tencent.com/developer/article/1489438
https://docs.konghq.com/getting-started-guide/latest/overview/