RussellLuo/caddy-ext

Custom error response

ermiaqasemi opened this issue · 5 comments

Hi thanks for developing this, it is too much useful

I just wondering how can I return a custom response when the limit happens?

FYI, I tried handle_errors but does not work

FYI, I tried handle_errors but does not work

While responding with a 429, rate_limit actually returns a nil error:

w.WriteHeader(rl.RejectStatusCode)
return nil

As explained in this issue: caddyserver/caddy#2920 (comment), handle_errors is for errors that happen in Caddy.

I think the ideal solution is to check whether the response status code is 429 first (unfortunately not supported by Caddy now); and If it's so, then we trigger an error explicitly by using the error directive:

@429 status 429
error @429 429

There is a similar response matcher status, which is only available in the context of reverse_proxy.

Thanks for explanation @RussellLuo

Hi @ermiaqasemi, rate_limit now will return an error if a rate limit is exceeded. Here is an example configuration:

:8080 {
  handle_errors {
    @429 expression `{http.error.status_code} == 429`
    respond @429 "The request is rejected!"
  }

  route /foo {
    rate_limit {remote.host} 1r/m

    respond 200
  }
}

Thanks @RussellLuo I will check