Merge branch 'main' of codeberg-u1f320:u1f320/pronouns.cc

This commit is contained in:
Sam 2023-03-13 01:09:02 +01:00
commit 51aacf861e
No known key found for this signature in database
GPG Key ID: B4EF20DDE721CAA1
1 changed files with 11 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package rate
import ( import (
"net/http" "net/http"
"os"
"sort" "sort"
"strings" "strings"
"time" "time"
@ -18,6 +19,7 @@ type Limiter struct {
options []httprate.Option options []httprate.Option
wildcardScopes []*scopedLimiter wildcardScopes []*scopedLimiter
frontendIP string
} }
type scopedLimiter struct { type scopedLimiter struct {
@ -32,6 +34,7 @@ func NewLimiter(defaultLimit int, windowLength time.Duration, options ...httprat
windowLength: windowLength, windowLength: windowLength,
options: options, options: options,
defaultLimiter: httprate.Limit(defaultLimit, windowLength, options...), defaultLimiter: httprate.Limit(defaultLimit, windowLength, options...),
frontendIP: os.Getenv("FRONTEND_IP"),
} }
} }
@ -65,6 +68,14 @@ func (l *Limiter) Handler() func(http.Handler) http.Handler {
func (l *Limiter) handle(next http.Handler) http.Handler { func (l *Limiter) handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if l.frontendIP != "" {
ip, err := httprate.KeyByIP(r)
if err == nil && ip == l.frontendIP {
// frontend gets to bypass ratelimit
next.ServeHTTP(w, r)
}
}
for _, s := range l.scopes { for _, s := range l.scopes {
if (r.Method == s.Method || s.Method == "*") && s.glob.Match(r.URL.Path) { if (r.Method == s.Method || s.Method == "*") && s.glob.Match(r.URL.Path) {
bucket := s.Pattern bucket := s.Pattern