// Go 有成熟的代理库
import (
"golang.org/x/net/proxy"
"github.com/Dreamacro/clash/adapter"
"github.com/Dreamacro/clash/transport/socks5"
)
// 使用 goroutine 处理并发测速
func testNodes(nodes []Node) {
semaphore := make(chan struct{}, 10) // 限制并发数
var wg sync.WaitGroup
for _, node := range nodes {
wg.Add(1)
go func(n Node) {
defer wg.Done()
semaphore <- struct{}{}
defer func() { <-semaphore }()
testNode(n)
}(node)
}
wg.Wait()
}
// Go 的网络库更底层,性能更好
func testLatency(node Node) (int, error) {
start := time.Now()
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", node.Server, node.Port), 10*time.Second)
if err != nil {
return 0, err
}
defer conn.Close()
return int(time.Since(start).Milliseconds()), nil
}
type SpeedTester struct {
nodes []Node
results chan TestResult
config *Config
}
type Node struct {
Name string
Type string
Server string
Port int
Password string
// 其他配置...
}
type ProxyAdapter interface {
TestLatency() (int, error)
TestSpeed() (float64, float64, error)
GetIP() (string, error)
}
// 为每种代理类型实现适配器
type ShadowsocksAdapter struct {
node *Node
}
type VMessAdapter struct {
node *Node
}
func (st *SpeedTester) TestAll() []TestResult {
results := make([]TestResult, 0, len(st.nodes))
resultChan := make(chan TestResult, len(st.nodes))
// 启动并发测速
for _, node := range st.nodes {
go func(n Node) {
result := st.testNode(n)
resultChan <- result
}(node)
}
// 收集结果
for i := 0; i < len(st.nodes); i++ {
results = append(results, <-resultChan)
}
return results
}
Go 语言确实更适合这个项目,因为:
建议采用 Go 重写核心测速功能,保留现有的数据库和前端架构。