gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/sync/time/ntp/ntp.go (about) 1 // Package ntp provides ntp synchronized time 2 package ntp 3 4 import ( 5 "context" 6 gotime "time" 7 8 "github.com/beevik/ntp" 9 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/time" 10 ) 11 12 type ntpTime struct { 13 server string 14 } 15 16 type ntpServerKey struct{} 17 18 func (n *ntpTime) Now() (gotime.Time, error) { 19 return ntp.Time(n.server) 20 } 21 22 // NewTime returns ntp time 23 func NewTime(opts ...time.Option) time.Time { 24 options := time.Options{ 25 Context: context.Background(), 26 } 27 28 for _, o := range opts { 29 o(&options) 30 } 31 32 server := "time.google.com" 33 34 if k, ok := options.Context.Value(ntpServerKey{}).(string); ok { 35 server = k 36 } 37 38 return &ntpTime{ 39 server: server, 40 } 41 } 42 43 // WithServer sets the ntp server 44 func WithServer(s string) time.Option { 45 return func(o *time.Options) { 46 if o.Context == nil { 47 o.Context = context.Background() 48 } 49 o.Context = context.WithValue(o.Context, ntpServerKey{}, s) 50 } 51 }