forked from h2non/imaginary
/
middleware.go
95 lines (80 loc) · 2.28 KB
/
middleware.go
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
package main
import (
"fmt"
"github.com/daaku/go.httpgzip"
"github.com/rs/cors"
"gopkg.in/h2non/bimg.v0"
"gopkg.in/throttled/throttled.v2"
"gopkg.in/throttled/throttled.v2/store/memstore"
"net/http"
)
func Middleware(fn func(http.ResponseWriter, *http.Request), o ServerOptions) http.Handler {
next := http.Handler(http.HandlerFunc(fn))
if o.Concurrency > 0 {
next = throttle(next, o)
}
if o.Gzip {
next = httpgzip.NewHandler(next)
}
if o.CORS {
next = cors.Default().Handler(next)
}
if o.ApiKey != "" {
next = authorizeClient(next, o.ApiKey)
}
return validate(defaultHeaders(next))
}
func ImageMiddleware(o ServerOptions) func(Operation) http.Handler {
return func(fn Operation) http.Handler {
return Middleware(imageControllerDispatcher(o, Operation(fn)), o)
}
}
func throttleError(err error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "throttle error: "+err.Error(), http.StatusInternalServerError)
})
}
func throttle(next http.Handler, o ServerOptions) http.Handler {
store, err := memstore.New(65536)
if err != nil {
return throttleError(err)
}
quota := throttled.RateQuota{throttled.PerSec(o.Concurrency), o.Burst}
rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
if err != nil {
return throttleError(err)
}
httpRateLimiter := throttled.HTTPRateLimiter{
RateLimiter: rateLimiter,
VaryBy: &throttled.VaryBy{Method: true},
}
return httpRateLimiter.RateLimit(next)
}
func validate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "POST" {
ErrorReply(w, ErrMethodNotAllowed)
return
}
next.ServeHTTP(w, r)
})
}
func authorizeClient(next http.Handler, validKey string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("API-Key")
if key == "" {
key = r.URL.Query().Get("key")
}
if key != validKey {
ErrorReply(w, ErrInvalidApiKey)
return
}
next.ServeHTTP(w, r)
})
}
func defaultHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", fmt.Sprintf("imaginary %s (bimg %s)", Version, bimg.Version))
next.ServeHTTP(w, r)
})
}