-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.clocks.go
70 lines (57 loc) · 1.48 KB
/
helpers.clocks.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
package main
import (
"time"
)
var (
_ Clocker = (*Clock)(nil) // ensure Clock implements Clocker
_ TickerClocker = (*TickClock)(nil) // ensure TickClock implements TickerClocker
)
// TickerClocker is an interface which can provides the current time and a ticker.
type TickerClocker interface {
Clocker
NewTicker(time.Duration) *time.Ticker
}
// Clocker is an interface for getting current real time.
// Refactoring: remove Zero from this interface. The create
// ZeroClocker which embeds Clock and Zero() method. Then
// TickerClocker can use Clocker without being forced to
// implement Zero() method.
type Clocker interface {
Now() time.Time
Zero() time.Time
}
// Clock implements the Clocker interface.
type Clock struct {
tz *time.Location
}
// NewClock returns a ready to use Clock with timezone sets
// to UTC in production environment and Local in dev env.
func NewClock(isProd bool) *Clock {
if isProd {
return &Clock{time.UTC}
}
return &Clock{time.Local}
}
// Now provides current clock time.
func (ck *Clock) Now() time.Time {
return time.Now().In(ck.tz)
}
// Zero returns zero time.
func (ck *Clock) Zero() time.Time {
return time.Time{}
}
type TickClock struct {
clock Clocker
}
func NewTickClock(ck Clocker) *TickClock {
return &TickClock{ck}
}
func (tc *TickClock) Now() time.Time {
return tc.clock.Now()
}
func (tc *TickClock) Zero() time.Time {
return tc.clock.Zero()
}
func (tc *TickClock) NewTicker(d time.Duration) *time.Ticker {
return time.NewTicker(d)
}