Skip to content

Commit

Permalink
feat(plugins): allow to set error code and error message
Browse files Browse the repository at this point in the history
  • Loading branch information
utix committed Oct 25, 2022
1 parent bc41123 commit 9c25da5
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion kong/plugins/rate-limiting/handler.lua
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ function RateLimitingHandler:access(conf)
if stop then
headers = headers or {}
headers[RETRY_AFTER] = reset
return kong.response.error(429, "API rate limit exceeded", headers)
return kong.response.error(conf.error_code, conf.error_message, headers)
end

if headers then
Expand Down
2 changes: 2 additions & 0 deletions kong/plugins/rate-limiting/schema.lua
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ return {
{ redis_timeout = { type = "number", default = 2000, }, },
{ redis_database = { type = "integer", default = 0 }, },
{ hide_client_headers = { type = "boolean", required = true, default = false }, },
{ error_code = {type = "number", default = 429, gt = 0 }, },
{ error_message = {type = "string", default = "API rate limit exceeded" }, },
},
custom_validator = validate_periods_order,
},
Expand Down
37 changes: 37 additions & 0 deletions spec/03-plugins/23-rate-limiting/04-access_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,28 @@ for _, strategy in helpers.each_strategy() do
},
})

local route6 = bp.routes:insert {
hosts = { "test6.com" },
}

bp.rate_limiting_plugins:insert({
route = { id = route6.id },
config = {
minute = 3,
policy = policy,
fault_tolerant = false,
redis_host = REDIS_HOST,
redis_port = redis_conf.redis_port,
redis_ssl = redis_conf.redis_ssl,
redis_ssl_verify = redis_conf.redis_ssl_verify,
redis_server_name = redis_conf.redis_server_name,
redis_password = REDIS_PASSWORD,
redis_database = REDIS_DATABASE,
error_code = 404,
error_message = "Not Found",
}
})

local service = bp.services:insert()
bp.routes:insert {
hosts = { "test-service1.com" },
Expand Down Expand Up @@ -556,6 +578,21 @@ for _, strategy in helpers.each_strategy() do
local json = cjson.decode(body)
assert.same({ message = "API rate limit exceeded" }, json)
end)

it_with_retry("blocks with a custom error code and message", function()
for i = 1, 3 do
GET("/status/200", {
headers = { Host = "test6.com" },
}, 200)
end
local res, body = GET("/status/200", {
path = "/status/200",
headers = { Host = "test6.com" },
}, 404)
assert.are.same(0, tonumber(res.headers["ratelimit-remaining"]))
local json = cjson.decode(body)
assert.same({ message = "Not Found" }, json)
end)
end)
describe("Without authentication (IP address)", function()
it_with_retry("blocks if exceeding limit #grpc", function()
Expand Down

0 comments on commit 9c25da5

Please sign in to comment.