runSpeedTestSimple 简单速度测试,返回 (峰值速度 kB/s, TCP延迟ms, 三字码头)
(ip string, port int, useTLS bool)
| 347 | |
| 348 | // runSpeedTestSimple 简单速度测试,返回 (峰值速度 kB/s, TCP延迟ms, 三字码头) |
| 349 | func runSpeedTestSimple(ip string, port int, useTLS bool) (int, int, string) { |
| 350 | var tcpMs int |
| 351 | transport := &http.Transport{ |
| 352 | DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 353 | start := time.Now() |
| 354 | conn, err := net.Dial("tcp", net.JoinHostPort(ip, strconv.Itoa(port))) |
| 355 | if err == nil { |
| 356 | tcpMs = int(time.Since(start).Milliseconds()) |
| 357 | } |
| 358 | return conn, err |
| 359 | }, |
| 360 | } |
| 361 | if useTLS { |
| 362 | transport.TLSClientConfig = &tls.Config{ServerName: speedTestDomain} |
| 363 | } |
| 364 | client := &http.Client{ |
| 365 | Transport: transport, |
| 366 | Timeout: 5 * time.Second, |
| 367 | } |
| 368 | |
| 369 | scheme := "http" |
| 370 | if useTLS { |
| 371 | scheme = "https" |
| 372 | } |
| 373 | testURL := fmt.Sprintf("%s://%s/%s", scheme, speedTestDomain, speedTestFile) |
| 374 | |
| 375 | resp, err := client.Get(testURL) |
| 376 | if err != nil { |
| 377 | return 0, 0, "" |
| 378 | } |
| 379 | defer resp.Body.Close() |
| 380 | |
| 381 | cfRay := resp.Header.Get("CF-RAY") |
| 382 | dataCenter := extractDataCenter(cfRay) |
| 383 | |
| 384 | buf := make([]byte, 32*1024) |
| 385 | var totalBytes int64 |
| 386 | var windowBytes int64 |
| 387 | windowStart := time.Now() |
| 388 | maxSpeed := 0 |
| 389 | |
| 390 | for { |
| 391 | n, err := resp.Body.Read(buf) |
| 392 | totalBytes += int64(n) |
| 393 | windowBytes += int64(n) |
| 394 | if err != nil { |
| 395 | break |
| 396 | } |
| 397 | |
| 398 | elapsed := time.Since(windowStart).Seconds() |
| 399 | if elapsed >= 1.0 { |
| 400 | speedKB := int(float64(windowBytes) / 1024 / elapsed) |
| 401 | if speedKB > maxSpeed { |
| 402 | maxSpeed = speedKB |
| 403 | } |
| 404 | windowBytes = 0 |
| 405 | windowStart = time.Now() |
| 406 | } |
no test coverage detected