-
Notifications
You must be signed in to change notification settings - Fork 3
/
net.go
68 lines (54 loc) · 1.15 KB
/
net.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
package time
import (
"time"
"github.com/alexfalkowski/go-service/errors"
"github.com/beevik/ntp"
"github.com/beevik/nts"
)
// Network for time.
type Network interface {
// Now from the network.
Now() (time.Time, error)
}
// NewNetwork for time.
func NewNetwork(cfg *Config) Network {
switch {
case !IsEnabled(cfg):
return &sysNetwork{}
case cfg.IsNTP():
return &ntpNetwork{c: cfg}
case cfg.IsNTS():
return &ntsNetwork{c: cfg}
default:
return &sysNetwork{}
}
}
type sysNetwork struct{}
func (*sysNetwork) Now() (time.Time, error) {
return time.Now(), nil
}
type ntpNetwork struct {
c *Config
}
func (n *ntpNetwork) Now() (time.Time, error) {
t, err := ntp.Time(n.c.Host)
return t, errors.Prefix("ntp time", err)
}
type ntsNetwork struct {
c *Config
}
func (n *ntsNetwork) Now() (time.Time, error) {
se, err := nts.NewSession(n.c.Host)
if err != nil {
return time.Now(), errors.Prefix("nts time", err)
}
r, err := se.Query()
if err != nil {
return time.Now(), errors.Prefix("nts time", err)
}
err = r.Validate()
if err != nil {
return time.Now(), errors.Prefix("nts time", err)
}
return time.Now().Add(r.ClockOffset), nil
}