proxy_helper.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package proxy_helper
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/url"
  6. "regexp"
  7. "time"
  8. )
  9. func ProxyTest(proxyAddr string) (Speed int, Status int, err error) {
  10. // 首先检测 proxyAddr 是否合法,必须是 http 的代理,不支持 https 代理
  11. re := regexp.MustCompile(`(http):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?`)
  12. result := re.FindAllStringSubmatch(proxyAddr, -1)
  13. if result == nil {
  14. err = errors.New("proxy address illegal, only support http://xx:xx")
  15. return 0, 0, err
  16. }
  17. // 检测代理iP访问地址
  18. var testUrl string
  19. testUrl = "http://google.com"
  20. // 解析代理地址
  21. proxy, err := url.Parse(proxyAddr)
  22. // 设置网络传输
  23. netTransport := &http.Transport{
  24. Proxy: http.ProxyURL(proxy),
  25. MaxIdleConnsPerHost: 10,
  26. ResponseHeaderTimeout: time.Second * time.Duration(5),
  27. }
  28. // 创建连接客户端
  29. httpClient := &http.Client{
  30. Timeout: time.Second * 10,
  31. Transport: netTransport,
  32. }
  33. begin := time.Now() //判断代理访问时间
  34. // 使用代理IP访问测试地址
  35. res, err := httpClient.Get(testUrl)
  36. if err != nil {
  37. return
  38. }
  39. defer res.Body.Close()
  40. speed := int(time.Now().Sub(begin).Nanoseconds() / 1000 / 1000) //ms
  41. // 判断是否成功访问,如果成功访问StatusCode应该为200
  42. if res.StatusCode != http.StatusOK {
  43. return
  44. }
  45. return speed, res.StatusCode, nil
  46. }