Skip to content

Commit

Permalink
change timeout param to ...int64
Browse files Browse the repository at this point in the history
  • Loading branch information
Meepoljdx committed Nov 28, 2023
1 parent bcb8c32 commit 5bfc859
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
21 changes: 15 additions & 6 deletions nux/ntp.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,21 +134,30 @@ func getTime(host string, version byte, timeout int64) (time.Time, error) {
return t, nil
}

func getTimeout(timeout []int64) int64 {
// If the timeout parameter is not provided or the timeout parameter is greater than 0
if len(timeout) != 1 {
return 5
} else {
return timeout[0]
}
}

// TimeV returns the "receive time" from the remote NTP server
// specifed as host. Use the NTP client mode with the requested
// version number (2, 3, or 4).
func NtpTimeV(host string, version byte, timeout int64) (time.Time, error) {
return getTime(host, version, timeout)
func NtpTimeV(host string, version byte, timeout ...int64) (time.Time, error) {
return getTime(host, version, getTimeout(timeout))
}

// Time returns the "receive time" from the remote NTP server
// specifed as host. NTP client mode version 4 is used.
func NtpTime(host string, timeout int64) (time.Time, error) {
return getTime(host, 4, timeout)
func NtpTime(host string, timeout ...int64) (time.Time, error) {
return getTime(host, 4, getTimeout(timeout))
}

// Time returns the "receive time" from the remote NTP server
// specifed as host. NTP client mode version 4 is used.
func NtpTwoTime(host string, timeout int64) (time.Time, time.Time, error) {
return getTwoTime(host, 4, timeout)
func NtpTwoTime(host string, timeout ...int64) (time.Time, time.Time, error) {
return getTwoTime(host, 4, getTimeout(timeout))
}
24 changes: 24 additions & 0 deletions nux/ntp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package nux

import (
"log"
"testing"
"time"
)

func TestNtpTime(t *testing.T) {
orgTime := time.Now()
log.Println("Begin")
serverReciveTime, serverTransmitTime, err := NtpTwoTime("ntp1.aliyun.com", 20)
if err != nil {
log.Println(err)
return
}
dstTime := time.Now()

// https://en.wikipedia.org/wiki/Network_Time_Protocol
duration := ((serverReciveTime.UnixNano() - orgTime.UnixNano()) + (serverTransmitTime.UnixNano() - dstTime.UnixNano())) / 2

delta := duration / 1e6 // convert to ms
log.Println(delta)
}

0 comments on commit 5bfc859

Please # to comment.