Skip to content

Commit

Permalink
Emit event when rate limit exceeded (close #63)
Browse files Browse the repository at this point in the history
  • Loading branch information
mholt committed Aug 28, 2024
1 parent 76d3984 commit 12435ec
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"time"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyevents"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/certmagic"
"go.uber.org/zap"
Expand Down Expand Up @@ -73,6 +74,8 @@ type Handler struct {
storage certmagic.Storage
random *weakrand.Rand
logger *zap.Logger
ctx caddy.Context
events *caddyevents.App
}

// CaddyModule returns the Caddy module information.
Expand All @@ -85,8 +88,15 @@ func (Handler) CaddyModule() caddy.ModuleInfo {

// Provision sets up the handler.
func (h *Handler) Provision(ctx caddy.Context) error {
h.ctx = ctx
h.logger = ctx.Logger(h)

eventsAppIface, err := ctx.App("events")
if err != nil {
return fmt.Errorf("getting events app: %v", err)
}
h.events = eventsAppIface.(*caddyevents.App)

if len(h.StorageRaw) > 0 {
val, err := ctx.LoadModule(h, "StorageRaw")
if err != nil {
Expand Down Expand Up @@ -218,6 +228,13 @@ func (h *Handler) rateLimitExceeded(w http.ResponseWriter, r *http.Request, repl
// Log the rate limit exceeded message
logger.Info("rate limit exceeded")

// also emit event so user can configure custom responses to rate limit violations
h.events.Emit(h.ctx, "rate_limit_exceeded", map[string]any{
"zone": zoneName,
"wait": wait,
"remote_ip": remoteIP,
})

// make some information about this rate limit available
repl.Set("http.rate_limit.exceeded.name", zoneName)

Expand Down

1 comment on commit 12435ec

@ta2013
Copy link

@ta2013 ta2013 commented on 12435ec Aug 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, thanks!

one small idea, nice to have emit logkey also?

Please sign in to comment.