xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / internal / server / limit.go 69 lines1.2 kB Raw
1package server
2
3import (
4	"net"
5	"net/http"
6	"strings"
7	"sync"
8	"time"
9)
10
11type rate struct{ per, burst float64 }
12
13var rates = map[string]rate{
14	"read":     {20, 80},
15	"act":      {8, 60},
16	"new":      {1.0 / 30, 10},
17	"feedback": {1.0 / 600, 3},
18}
19
20type bucket struct {
21	tokens float64
22	last   time.Time
23}
24
25type limiter struct {
26	mu      sync.Mutex
27	buckets map[string]*bucket
28}
29
30func (l *limiter) allow(ip, kind string) bool {
31	if ip == "" {
32		return true
33	}
34	r := rates[kind]
35	now := time.Now()
36	l.mu.Lock()
37	defer l.mu.Unlock()
38	if l.buckets == nil || len(l.buckets) > 20000 {
39		l.buckets = map[string]*bucket{}
40	}
41	b := l.buckets[kind+" "+ip]
42	if b == nil {
43		b = &bucket{tokens: r.burst, last: now}
44		l.buckets[kind+" "+ip] = b
45	}
46	b.tokens = min(r.burst, b.tokens+now.Sub(b.last).Seconds()*r.per)
47	b.last = now
48	if b.tokens < 1 {
49		return false
50	}
51	b.tokens--
52	return true
53}
54
55func clientIP(r *http.Request) string {
56	host, _, err := net.SplitHostPort(r.RemoteAddr)
57	if err != nil {
58		host = r.RemoteAddr
59	}
60	if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
61		return host
62	}
63	xff := r.Header.Get("X-Forwarded-For")
64	if xff == "" {
65		return ""
66	}
67	parts := strings.Split(xff, ",")
68	return strings.TrimSpace(parts[len(parts)-1])
69}