mirror of
https://github.com/samsonjs/rack-attack.git
synced 2026-04-27 15:07:41 +00:00
README: add example for returning X-RateLimit-* headers
This commit is contained in:
parent
7860a82b5a
commit
b07537d51e
1 changed files with 28 additions and 7 deletions
35
README.md
35
README.md
|
|
@ -230,19 +230,40 @@ Rack::Attack.blocklisted_response = lambda do |env|
|
||||||
end
|
end
|
||||||
|
|
||||||
Rack::Attack.throttled_response = lambda do |env|
|
Rack::Attack.throttled_response = lambda do |env|
|
||||||
# name and other data about the matched throttle
|
# NB: you have access to the name and other data about the matched throttle
|
||||||
body = [
|
# env['rack.attack.matched'],
|
||||||
env['rack.attack.matched'],
|
# env['rack.attack.match_type'],
|
||||||
env['rack.attack.match_type'],
|
# env['rack.attack.match_data']
|
||||||
env['rack.attack.match_data']
|
|
||||||
].inspect
|
|
||||||
|
|
||||||
# Using 503 because it may make attacker think that they have successfully
|
# Using 503 because it may make attacker think that they have successfully
|
||||||
# DOSed the site. Rack::Attack returns 429 for throttling by default
|
# DOSed the site. Rack::Attack returns 429 for throttling by default
|
||||||
[ 503, {}, [body]]
|
[ 503, {}, ["Server Error\n"]]
|
||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### X-RateLimit headers for well-behaved clients
|
||||||
|
|
||||||
|
While Rack::Attack's primary focus is minimizing harm from abusive clients, it
|
||||||
|
can also be used to return rate limit data that's helpful for well-behaved clients.
|
||||||
|
|
||||||
|
Here's an example response that includes conventional `X-RateLimit-*` headers:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
Rack::Attack.throttled_response = lambda do |env|
|
||||||
|
now = Time.now
|
||||||
|
match_data = env['rack.attack.match_data']
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'X-RateLimit-Limit' => match_data[:limit].to_s,
|
||||||
|
'X-RateLimit-Remaining' => '0',
|
||||||
|
'X-RateLimit-Reset' => (now + (match_data[:period] - now.to_i % match_data[:period])).to_s
|
||||||
|
}
|
||||||
|
|
||||||
|
[ 429, headers, ["Throttled\n"]]
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
For responses that did not exceed a throttle limit, Rack::Attack annotates the env with match data:
|
For responses that did not exceed a throttle limit, Rack::Attack annotates the env with match data:
|
||||||
|
|
||||||
```ruby
|
```ruby
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue