Skip to content

Instantly share code, notes, and snippets.

@Jinnrry
Created January 3, 2024 05:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jinnrry/962bf7f5cf06355baf039fe3281dd9fd to your computer and use it in GitHub Desktop.
Save Jinnrry/962bf7f5cf06355baf039fe3281dd9fd to your computer and use it in GitHub Desktop.
func httpPing(url string, count int) (int, float64) {
client := &http.Client{
Timeout: 2 * time.Second,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 2 * time.Second,
KeepAlive: -1,
}).DialContext,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
startTime := time.Now().UnixMilli()
errNum := 0
for i := 0; i < count; i++ {
_, err := client.Get(url)
if err != nil {
errNum++
}
}
endTime := time.Now().UnixMilli()
spend := (endTime - startTime) / int64(count)
return int(spend), float64(errNum) / float64(count)
}
func TcpPing(host string, count int) (int64, float64) {
start := time.Now().UnixMilli()
failNum := 0
for i := 0; i < count; i++ {
d := net.Dialer{Timeout: 2 * time.Second}
conn, err := d.Dial("tcp", host)
if err != nil {
failNum++
}
if conn != nil {
conn.Close()
}
}
spendTime := time.Now().UnixMilli() - start
if failNum == count {
return 0, 1
}
return spendTime / int64(count), float64(failNum) / float64(count)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment