forked from SagerNet/LibSagerNetCore
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathurltest.go
More file actions
62 lines (58 loc) · 1.93 KB
/
urltest.go
File metadata and controls
62 lines (58 loc) · 1.93 KB
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
package libcore
import (
"context"
"fmt"
"github.com/pkg/errors"
v2rayNet "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/core"
"net"
"net/http"
"time"
)
func urlTest(dialContext func(ctx context.Context, network, addr string) (net.Conn, error), link string, timeout int32) (int32, error) {
transport := &http.Transport{
TLSHandshakeTimeout: time.Duration(timeout) * time.Millisecond,
DisableKeepAlives: true,
DialContext: dialContext,
}
req, err := http.NewRequestWithContext(context.Background(), "GET", link, nil)
req.Header.Set("User-Agent", "curl/7.74.0")
if err != nil {
return 0, errors.WithMessage(err, "create get request")
}
start := time.Now()
resp, err := (&http.Client{
Transport: transport,
Timeout: time.Duration(timeout) * time.Millisecond,
}).Do(req)
if err == nil && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
err = fmt.Errorf("unexcpted response status: %d", resp.StatusCode)
}
if err != nil {
return 0, err
}
return int32(time.Since(start).Milliseconds()), nil
}
func UrlTestV2ray(instance *V2RayInstance, inbound string, link string, timeout int32) (int32, error) {
return urlTest(func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := v2rayNet.ParseDestination(fmt.Sprintf("%s:%s", network, addr))
if err != nil {
return nil, err
}
if inbound != "" {
ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: inbound})
}
return core.Dial(ctx, instance.core, dest)
}, link, timeout)
}
func UrlTestClashBased(instance *ClashBasedInstance, link string, timeout int32) (int32, error) {
return urlTest(func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := addrToMetadata(addr)
if err != nil {
return nil, err
}
dest.NetWork = networkForClash(network)
return instance.out.DialContext(ctx, dest)
}, link, timeout)
}