This repository has been archived by the owner on Jul 11, 2020. It is now read-only.
forked from fiorix/freegeoip
/
ratelimit.go
96 lines (84 loc) · 2.47 KB
/
ratelimit.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
96
// Copyright 2009-2015 The freegeoip authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package apiserver
import (
"errors"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/fiorix/go-redis/redis"
)
var (
errQuotaExceeded = errors.New("Quota exceeded")
errRedisUnavailable = errors.New("Try again later")
)
// A KeyMaker makes keys from the http.Request object to the RateLimiter.
type KeyMaker interface {
KeyFor(r *http.Request) string
}
// KeyMakerFunc is an adapter function for KeyMaker.
type KeyMakerFunc func(r *http.Request) string
// KeyFor implements the KeyMaker interface.
func (f KeyMakerFunc) KeyFor(r *http.Request) string {
return f(r)
}
// DefaultKeyMaker is a KeyMaker that returns the client IP
// address from http.Request.RemoteAddr.
var DefaultKeyMaker = KeyMakerFunc(func(r *http.Request) string {
addr, _, _ := net.SplitHostPort(r.RemoteAddr)
return addr
})
// A RateLimiter is an http.Handler that wraps another handler,
// and calls it up to a certain limit, max per interval.
type RateLimiter struct {
Redis *redis.Client
Max int
Interval time.Duration
KeyMaker KeyMaker
Handler http.Handler
secInterval int
once sync.Once
}
// ServeHTTP implements the http.Handler interface.
func (rl *RateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rl.once.Do(func() {
rl.secInterval = int(rl.Interval.Seconds())
if rl.KeyMaker == nil {
rl.KeyMaker = DefaultKeyMaker
}
})
status, err := rl.do(w, r)
if err != nil {
http.Error(w, err.Error(), status)
return
}
}
func (rl *RateLimiter) do(w http.ResponseWriter, r *http.Request) (int, error) {
k := rl.KeyMaker.KeyFor(r)
nreq, err := rl.Redis.Incr(k)
if err != nil {
return http.StatusServiceUnavailable, errRedisUnavailable
}
var ttl = 0
if nreq == 1 {
if _, err = rl.Redis.Expire(k, rl.secInterval); err != nil {
return http.StatusServiceUnavailable, errRedisUnavailable
}
ttl = rl.secInterval
} else if ttl, err = rl.Redis.TTL(k); err != nil {
return http.StatusServiceUnavailable, errRedisUnavailable
}
rem := rl.Max - nreq
w.Header().Set("X-RateLimit-Limit", strconv.Itoa(rl.Max))
w.Header().Set("X-RateLimit-Reset", strconv.Itoa(ttl))
if rem < 0 {
w.Header().Set("X-RateLimit-Remaining", "0")
return http.StatusForbidden, errQuotaExceeded
}
w.Header().Set("X-RateLimit-Remaining", strconv.Itoa(rem))
rl.Handler.ServeHTTP(w, r)
return http.StatusOK, nil
}