-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
119 lines (103 loc) · 2.99 KB
/
middleware.go
File metadata and controls
119 lines (103 loc) · 2.99 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package cachegrid
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// HTTPRateLimit returns an HTTP middleware that rate limits by client IP.
func HTTPRateLimit(c *Cache, limit int64, window time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
key := "ratelimit:" + ip
allowed, state := c.RateLimit(key, RateLimitOptions{Limit: limit, Window: window})
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", state.Limit))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", state.Remaining))
w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", state.ResetsAt.Unix()))
if !allowed {
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}
// HTTPCache returns an HTTP middleware that caches responses.
func HTTPCache(c *Cache, ttl time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
next.ServeHTTP(w, r)
return
}
cacheKey := "httpcache:" + hashRequest(r)
var cached cachedResponse
if c.Get(cacheKey, &cached) {
for k, v := range cached.Headers {
w.Header().Set(k, v)
}
w.Header().Set("X-Cache", "HIT")
w.WriteHeader(cached.StatusCode)
w.Write(cached.Body)
return
}
rec := &responseRecorder{
ResponseWriter: w,
body: &bytes.Buffer{},
statusCode: http.StatusOK,
}
next.ServeHTTP(rec, r)
if rec.statusCode >= 200 && rec.statusCode < 400 {
resp := cachedResponse{
StatusCode: rec.statusCode,
Body: rec.body.Bytes(),
Headers: make(map[string]string),
}
for k := range w.Header() {
resp.Headers[k] = w.Header().Get(k)
}
c.Set(cacheKey, resp, ttl)
}
w.Header().Set("X-Cache", "MISS")
})
}
}
type cachedResponse struct {
StatusCode int `msgpack:"status_code"`
Body []byte `msgpack:"body"`
Headers map[string]string `msgpack:"headers"`
}
type responseRecorder struct {
http.ResponseWriter
body *bytes.Buffer
statusCode int
}
func (rec *responseRecorder) WriteHeader(code int) {
rec.statusCode = code
rec.ResponseWriter.WriteHeader(code)
}
func (rec *responseRecorder) Write(b []byte) (int, error) {
rec.body.Write(b)
return rec.ResponseWriter.Write(b)
}
func clientIP(r *http.Request) string {
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
parts := strings.SplitN(forwarded, ",", 2)
return strings.TrimSpace(parts[0])
}
if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
return realIP
}
host, _, _ := strings.Cut(r.RemoteAddr, ":")
return host
}
func hashRequest(r *http.Request) string {
h := sha256.New()
io.WriteString(h, r.Method)
io.WriteString(h, r.URL.String())
return fmt.Sprintf("%x", h.Sum(nil))[:16]
}