Skip to content

net/http middleware

Protect standard-library handlers while keeping key extraction and denial responses configurable.

Prerequisites

  • Go 1.24 or newer
  • port 8080 available

Run

go run ./examples/http
examples/http/main.go
// Package main demonstrates using GoRL with the standard net/http middleware.
package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/AliRizaAynaci/gorl/v2"
    "github.com/AliRizaAynaci/gorl/v2/core"
    mw "github.com/AliRizaAynaci/gorl/v2/middleware/http"
)

func main() {
    limiter, err := gorl.New(core.Config{
        Strategy: core.SlidingWindow,
        Limit:    5,
        Window:   30 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer limiter.Close()

    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello from %s!\n", r.URL.Path)
    })

    mux := http.NewServeMux()
    mux.Handle("/api/", mw.RateLimit(limiter, mw.Options{
        KeyFunc: mw.KeyByIP(),
    }, handler))

    log.Println("Listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Exercise the endpoint from another terminal:

for i in 1 2 3 4 5 6; do curl -i http://localhost:8080/api/demo; done

Expected behavior

The first five requests from one IP are allowed inside the thirty-second sliding window. The sixth receives HTTP 429. Responses include limit and remaining headers; positive reset and retry durations add their corresponding headers.

Production cautions

KeyByIP() reads forwarding headers without validating the proxy. Normalize them at a trusted edge or provide a topology-aware key function. Always provide Options.KeyFunc; it is required by the standard-library adapter.