Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

load_balanced_socks5.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package network
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "net/url"
  8. )
  9. type loadBalancedSocks5Dialer struct {
  10. dialers []Dialer
  11. }
  12. func (l loadBalancedSocks5Dialer) Dial(network, address string) (net.Conn, error) {
  13. return l.DialContext(context.Background(), network, address)
  14. }
  15. func (l loadBalancedSocks5Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
  16. length := len(l.dialers)
  17. start := rand.Intn(length)
  18. moved := false
  19. for i := start; i != start || !moved; i = (i + 1) % length {
  20. moved = true
  21. if conn, err := l.dialers[i].DialContext(ctx, network, address); err == nil {
  22. return conn, nil
  23. }
  24. }
  25. return nil, ErrCannotDialWithAllProxies
  26. }
  27. // NewLoadBalancedSocks5Dialer builds a new load balancing SOCKS5
  28. // dialer.
  29. //
  30. // The main difference from one which is made by NewSocks5Dialer is that
  31. // we actually have a list of these proxies. When dial is requested,
  32. // any proxy is picked and used. If proxy fails for some reason, we try
  33. // another one.
  34. //
  35. // So, it is mostly useful if you have some routes with proxies which
  36. // are not always online or having buggy network.
  37. func NewLoadBalancedSocks5Dialer(baseDialer Dialer, proxyURLs []*url.URL) (Dialer, error) {
  38. dialers := make([]Dialer, 0, len(proxyURLs))
  39. for _, u := range proxyURLs {
  40. dialer, err := NewSocks5Dialer(newProxyDialer(baseDialer, u), u)
  41. if err != nil {
  42. return nil, fmt.Errorf("cannot build dialer for %s: %w", u.String(), err)
  43. }
  44. dialers = append(dialers, dialer)
  45. }
  46. return loadBalancedSocks5Dialer{
  47. dialers: dialers,
  48. }, nil
  49. }