proxyservice.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "time"
  10. )
  11. const (
  12. watchInterval = 10
  13. base64Table = "ABNOPqrceQRSTklmUDEFGXYZabnopfghHVWdijstuvwCIJKLMxyz0123456789+/"
  14. )
  15. var (
  16. coder = base64.NewEncoding(base64Table)
  17. )
  18. // reloadProxies 重新加载代理池
  19. func reloadProxies() {
  20. fmt.Print("请求远程proxy service")
  21. resp, err := http.Get("http://proxy.spdata.jianyu360.com/proxy/getallip")
  22. if err != nil {
  23. fmt.Print(err.Error())
  24. return
  25. }
  26. bs, err := ioutil.ReadAll(resp.Body)
  27. if err != nil {
  28. fmt.Print(err.Error())
  29. return
  30. }
  31. resp.Body.Close()
  32. data := make([]*IpItem, 0, 0)
  33. newPool := make([]*IpItem, 0, 0)
  34. err = json.Unmarshal(bs, &data)
  35. if err != nil {
  36. fmt.Print(err.Error())
  37. return
  38. }
  39. index := 0
  40. //5分钟以内过期的都不要
  41. lifeTimieout := time.Now().Unix() + 5*60
  42. for _, v := range data {
  43. fmt.Print(">")
  44. if v.LifeTime <= lifeTimieout {
  45. fmt.Print("O")
  46. continue
  47. }
  48. rawIp, err := coder.DecodeString(v.Ip)
  49. if err != nil {
  50. continue
  51. }
  52. ipStr := string(rawIp)
  53. v.Ip = ipStr
  54. for _, p := range v.Ports {
  55. addr := ipStr + ":" + p
  56. if checkDial(addr) {
  57. fmt.Print("+")
  58. v.Raw = addr
  59. break
  60. } else {
  61. fmt.Print("?")
  62. }
  63. }
  64. if v.Raw != "" {
  65. v.Index = index
  66. index += 1
  67. newPool = append(newPool, v)
  68. }
  69. }
  70. if len(newPool) > 0 {
  71. roulette.Init(newPool)
  72. fmt.Printf("--{proxy size %d}--", roulette.Length)
  73. } else {
  74. fmt.Print("远程服务没有返回有效proxy")
  75. }
  76. }
  77. // checkDial 检查是否能tcp连接通
  78. func checkDial(addr string) bool {
  79. conn, err := net.DialTimeout("tcp", addr, 1*time.Second)
  80. if err == nil {
  81. conn.Close()
  82. }
  83. return err == nil
  84. }
  85. func watch() {
  86. for {
  87. time.Sleep(time.Duration(int64(watchInterval)) * time.Minute)
  88. reloadProxies()
  89. }
  90. }