初始化提交
This commit is contained in:
56
mengyamonitor-backend/latency.go
Normal file
56
mengyamonitor-backend/latency.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LatencyInfo 延迟信息
|
||||
type LatencyInfo struct {
|
||||
ClientToServer float64 `json:"clientToServer"` // 客户端到服务器延迟(ms),由前端计算
|
||||
External map[string]string `json:"external"` // 外部网站延迟
|
||||
}
|
||||
|
||||
// checkExternalLatency 检测外部网站延迟
|
||||
func checkExternalLatency(host string, timeout time.Duration) string {
|
||||
start := time.Now()
|
||||
|
||||
// 尝试 TCP 连接 80 端口
|
||||
conn, err := net.DialTimeout("tcp", host+":80", timeout)
|
||||
if err != nil {
|
||||
// 如果 80 端口失败,尝试 443 (HTTPS)
|
||||
conn, err = net.DialTimeout("tcp", host+":443", timeout)
|
||||
if err != nil {
|
||||
return "超时"
|
||||
}
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
latency := time.Since(start).Milliseconds()
|
||||
|
||||
// 检查是否超时(超过超时时间的一半就认为可能有问题)
|
||||
if latency > timeout.Milliseconds()/2 {
|
||||
return "超时"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%d ms", latency)
|
||||
}
|
||||
|
||||
// readExternalLatencies 读取外部网站延迟
|
||||
func readExternalLatencies() map[string]string {
|
||||
latencies := make(map[string]string)
|
||||
timeout := 3 * time.Second
|
||||
|
||||
// 检测百度
|
||||
latencies["baidu.com"] = checkExternalLatency("baidu.com", timeout)
|
||||
|
||||
// 检测谷歌
|
||||
latencies["google.com"] = checkExternalLatency("google.com", timeout)
|
||||
|
||||
// 检测 GitHub
|
||||
latencies["github.com"] = checkExternalLatency("github.com", timeout)
|
||||
|
||||
return latencies
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user