https://github.com/Kong/kong/tree/master/kong/plugins/request-termination

handler.lua

  1. local kong = kong
  2. local DEFAULT_RESPONSE = {
  3. [401] = "Unauthorized",
  4. [404] = "Not found",
  5. [405] = "Method not allowed",
  6. [500] = "An unexpected error occurred",
  7. [502] = "Bad Gateway",
  8. [503] = "Service unavailable",
  9. }
  10. local RequestTerminationHandler = {}
  11. RequestTerminationHandler.PRIORITY = 2
  12. RequestTerminationHandler.VERSION = "2.0.1"
  13. function RequestTerminationHandler:access(conf)
  14. local status = conf.status_code
  15. local content = conf.body
  16. if content then
  17. local headers = {
  18. ["Content-Type"] = conf.content_type
  19. }
  20. return kong.response.exit(status, content, headers)
  21. end
  22. local message = conf.message or DEFAULT_RESPONSE[status]
  23. return kong.response.exit(status, message and { message = message } or nil)
  24. end
  25. return RequestTerminationHandler

schema.lua

  1. local typedefs = require "kong.db.schema.typedefs"
  2. local is_present = function(v)
  3. return type(v) == "string" and #v > 0
  4. end
  5. return {
  6. name = "request-termination",
  7. fields = {
  8. { protocols = typedefs.protocols_http },
  9. { config = {
  10. type = "record",
  11. fields = {
  12. { status_code = {
  13. type = "integer",
  14. default = 503,
  15. between = { 100, 599 },
  16. }, },
  17. { message = { type = "string" }, },
  18. { content_type = { type = "string" }, },
  19. { body = { type = "string" }, },
  20. },
  21. custom_validator = function(config)
  22. if is_present(config.message)
  23. and(is_present(config.content_type)
  24. or is_present(config.body)) then
  25. return nil, "message cannot be used with content_type or body"
  26. end
  27. if is_present(config.content_type)
  28. and not is_present(config.body) then
  29. return nil, "content_type requires a body"
  30. end
  31. return true
  32. end,
  33. },
  34. },
  35. },
  36. }
参数 默认值 描述
name 要使用的插件的名称,在本例中为ip-restriction
service_id 此插件将定位的 Service 的ID。
route_id 此插件将定位的 Route 的ID。
enabled true 是否将应用此插件。
consumer_id 此插件将定位的Consumer的id
config.status_code
optional
要发送的响应代码。
config.message
optional
要使用默认响应生成器发送的消息。
config.body
optional
要发送的原始响应body,这与config.message字段互斥。
config.content_type
optional
application/json; charset=utf-8 使用config.body配置的原始响应的Content type。

使用后,将通过发送配置的响应立即终止每个请求(在 Service, Route, Consumer, 或全局的已配置插件范围内)。

使用示例

  • 暂时禁用 Service(例如,它正在维护中)。
  • 暂时禁用 Route(例如,服务的其余部分已启动并正在运行,但必须禁用特定端点)。
  • 暂时禁用 Consumer(例如过度消费)。
  • 在逻辑OR设置中使用多个auth插件阻止匿名访问。