Brijesh's Git Server — toolkit @ 07f7705d52a615e47c3440f848a64abd85da22b1

my attempt at building my own web framework so I feel more confident when using chi

middleware/rate_limiter.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
package middleware

import (
	"net/http"
	"sync"
	"time"
)

type Middleware func(http.Handler) http.Handler

type rateLimiter struct {
	resetTime     time.Time
	requests      int
	maxRequests   int
	resetDuration time.Duration
	mu            sync.Mutex
}

func newRateLimiter(maxRequests int, duration time.Duration) *rateLimiter {
	return &rateLimiter{
		maxRequests:   maxRequests,
		resetDuration: duration,
		resetTime:     time.Now().Add(duration),
	}
}

func (rl *rateLimiter) allow() bool {
	rl.mu.Lock()
	defer rl.mu.Unlock()

	if time.Now().After(rl.resetTime) {
		rl.requests = 0
		rl.resetTime = time.Now().Add(rl.resetDuration)
	}

	if rl.requests >= rl.maxRequests {
		return false
	}

	rl.requests++
	return true
}

func RateLimit(maxRequests int, duration time.Duration) Middleware {
	limiter := newRateLimiter(maxRequests, duration)

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if !limiter.allow() {
				http.Error(w, "Too many requests", http.StatusTooManyRequests)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}