-
Notifications
You must be signed in to change notification settings - Fork 10
/
hashers.go
71 lines (57 loc) · 1.74 KB
/
hashers.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
package speedbump
import (
"strconv"
"time"
"github.com/facebookgo/clock"
)
// PerSecondHasher generates hashes per second. This means you can keep track
// of N request per second.
type PerSecondHasher struct {
// Clock is the time reference that will be used by the hasher. If it is
// not provided, the hashing function will use the default time. This can
// be replaced with a mock clock object for testing.
Clock clock.Clock
}
// Hash generates the hash for the current period and client.
func (h PerSecondHasher) Hash(id string) string {
if h.Clock == nil {
h.Clock = clock.New()
}
return id + ":" + strconv.FormatInt(h.Clock.Now().Unix(), 10)
}
// Duration gets the duration of each period.
func (h PerSecondHasher) Duration() time.Duration {
return time.Second
}
// PerMinuteHasher generates hashes per minute. This means you can keep track
// of N request per minute.
type PerMinuteHasher struct {
Clock clock.Clock
}
// Hash generates the hash for the current period and client.
func (h PerMinuteHasher) Hash(id string) string {
if h.Clock == nil {
h.Clock = clock.New()
}
return id + ":" + h.Clock.Now().Format("2006-01-02T15:04")
}
// Duration gets the duration of each period.
func (h PerMinuteHasher) Duration() time.Duration {
return time.Minute
}
// PerHourHasher generates hashes per hour. This means you can keep track
// of N request per hour.
type PerHourHasher struct {
Clock clock.Clock
}
// Hash generates the hash for the current period and client.
func (h PerHourHasher) Hash(id string) string {
if h.Clock == nil {
h.Clock = clock.New()
}
return id + ":" + h.Clock.Now().Format("2006-01-02T15")
}
// Duration gets the duration of each period.
func (h PerHourHasher) Duration() time.Duration {
return time.Hour
}