kong自定義插件實現——使用post發送請求

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/

下一篇kong插件的部署

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章