forked from MatsuriDayo/Matsuri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeedtest.go
74 lines (63 loc) · 1.77 KB
/
speedtest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package libcore
import (
"context"
"fmt"
"libcore/device"
"log"
"math/rand"
"net/http"
"strings"
"time"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
)
func UrlTestV2ray(instance *V2RayInstance, inbound string, link string, timeout int32) (int32, error) {
defer device.DeferPanicToError("UrlTestV2ray", func(err error) { log.Println(err) })
transport := &http.Transport{
TLSHandshakeTimeout: time.Duration(timeout) * time.Millisecond,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
// I believe the server...
dest, err := net.ParseDestination(fmt.Sprintf("%s:%s", network, addr))
if err != nil {
return nil, err
}
if inbound != "" {
ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: inbound})
}
return instance.DialContext(ctx, dest)
},
}
// Keep alive, use one connection
client := &http.Client{
Transport: transport,
Timeout: time.Duration(timeout) * time.Millisecond,
}
// Test handshake time
var time_start time.Time
var times = 1
var rtt_times = 1
// Test RTT "true delay"
if link2 := strings.TrimLeft(link, "true"); link != link2 {
link = link2
times = 3
rtt_times = 2
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", link, nil)
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", rand.Int()%84, rand.Int()%2))
if err != nil {
return 0, err
}
for i := 0; i < times; i++ {
if i == 1 || times == 1 {
time_start = time.Now()
}
resp, err := client.Do(req)
if err != nil {
return 0, err
}
resp.Body.Close()
}
return int32(time.Since(time_start).Milliseconds() / int64(rtt_times)), nil
}