修复无v6网络下的连接问题

This commit is contained in:
tsosunchia
2023-10-12 17:41:48 +08:00
parent 3164acfccf
commit 960ab9687c

View File

@@ -21,6 +21,7 @@ type ResponseInfo struct {
var (
results = make(chan ResponseInfo)
timeout = 5 * time.Second
)
var FastIpCache = ""
@@ -38,6 +39,11 @@ func GetFastIP(domain string, port string, enableOutput bool) string {
log.Fatal("DNS resolution failed, please check your system DNS Settings")
}
if len(ips) == 0 {
// 添加默认IP 45.88.195.154
ips = append(ips, net.ParseIP("45.88.195.154"))
}
for _, ip := range ips {
go checkLatency(domain, ip.String(), port)
}
@@ -46,21 +52,22 @@ func GetFastIP(domain string, port string, enableOutput bool) string {
select {
case result = <-results:
case <-time.After(1 * time.Second):
log.Fatal("IP connection has been timeout, please check your network")
//等待5s没有结果 视为连不上API了
case <-time.After(timeout):
log.Println("IP connection has been timeout, please check your network")
}
if len(ips) > 0 {
if enableOutput {
_, _ = fmt.Fprintf(color.Output, "%s prefered API IP - %s - %s - %s",
color.New(color.FgWhite, color.Bold).Sprintf("[NextTrace API]"),
color.New(color.FgGreen, color.Bold).Sprintf("%s", result.IP),
color.New(color.FgCyan, color.Bold).Sprintf("%sms", result.Latency),
color.New(color.FgGreen, color.Bold).Sprintf("%s", result.Content),
)
}
//if len(ips) > 0 {
if enableOutput {
_, _ = fmt.Fprintf(color.Output, "%s prefered API IP - %s - %s - %s",
color.New(color.FgWhite, color.Bold).Sprintf("[NextTrace API]"),
color.New(color.FgGreen, color.Bold).Sprintf("%s", result.IP),
color.New(color.FgCyan, color.Bold).Sprintf("%sms", result.Latency),
color.New(color.FgGreen, color.Bold).Sprintf("%s", result.Content),
)
}
//}
FastIpCache = result.IP
return result.IP
}
@@ -79,31 +86,32 @@ func checkLatency(domain string, ip string, port string) {
TLSClientConfig: &tls.Config{
ServerName: domain,
},
TLSHandshakeTimeout: 1 * time.Second,
TLSHandshakeTimeout: timeout,
}
client := &http.Client{
Transport: transport,
Timeout: 2 * time.Second,
Timeout: timeout,
}
//此处虽然是 https://domain/ 但是实际上会使用指定的IP连接
req, err := http.NewRequest("GET", "https://"+ip+":"+port+"/", nil)
if err != nil {
results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
// !!! 此处不要给results返回任何值
//results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
return
}
req.Host = domain
resp, err := client.Do(req)
if err != nil {
results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
//results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
return
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
//results <- ResponseInfo{IP: ip, Latency: "error", Content: ""}
return
}
bodyString := string(bodyBytes)