Skip to content

Commit

Permalink
Use duration for WindowLength
Browse files Browse the repository at this point in the history
  • Loading branch information
pic committed Nov 26, 2020
1 parent 1cd69d9 commit 45bd8b1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
22 changes: 15 additions & 7 deletions caddyfile.go
Expand Up @@ -16,6 +16,7 @@ package ratelimit

import (
"fmt"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
Expand All @@ -33,21 +34,28 @@ func (rl *RateLimit) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.NextBlock(0) {
switch d.Val() {
case "by_header":
d.NextArg()
if !d.NextArg() {
return d.ArgErr()
}
rl.ByHeader = d.Val()
case "max_requests":
d.NextArg()
if !d.NextArg() {
return d.ArgErr()
}
if num, err := strconv.Atoi(d.Val()); err != nil {
return fmt.Errorf("max requests unit %v could not be parsed as a number", d.Val())
return fmt.Errorf("max requests %v could not be parsed as a number", d.Val())
} else {
rl.MaxRequests = int64(num)
}
case "window_length":
d.NextArg()
if num, err := strconv.Atoi(d.Val()); err != nil {
return fmt.Errorf("window_length unit %v could not be parsed as a number", d.Val())
if !d.NextArg() {
return d.ArgErr()
}
duration, err := caddy.ParseDuration(d.Val())
if err != nil {
return fmt.Errorf("window_length %v could not be parsed as a duration", d.Val())
} else {
rl.WindowLength = int64(num)
rl.WindowLength = caddy.Duration(duration)

This comment has been minimized.

Copy link
@francislavoie

francislavoie Nov 27, 2020

Just a tip: else is unnecessary because you already return in the if condition. You can untab one step, reads cleaner.

}
default:
return d.Errf("unrecognized servers option '%s'", d.Val())
Expand Down
8 changes: 4 additions & 4 deletions ratelimit.go
Expand Up @@ -24,11 +24,11 @@ func init() {
type RateLimit struct {
ByHeader string `json:"by_header,omitempty"`

// window length for request rate checking (>= 1 minute)
WindowLength int64 `json:"window_length"`
// window length for request rate checking (better >= 2 minutes)
WindowLength caddy.Duration `json:"window_length,omitempty"`

// max request that should be processed per key in a given windowDuration
MaxRequests int64 `json:"max_requests"`
MaxRequests int64 `json:"max_requests,omitempty"`

// current window's request count per key
currentWindow *RequestCountTracker
Expand All @@ -53,7 +53,7 @@ func (rl *RateLimit) Provision(_ctx caddy.Context) error {
}

func (rl *RateLimit) windowDuration() time.Duration {
return time.Duration(rl.WindowLength) * time.Second
return time.Duration(rl.WindowLength)
}

// CaddyModule returns the Caddy module information.
Expand Down

0 comments on commit 45bd8b1

Please sign in to comment.