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
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

load_balanced_socks5.go 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. func NewLoadBalancedSocks5Dialer(baseDialer Dialer, proxyURLs []*url.URL) (Dialer, error) {
  28. dialers := make([]Dialer, 0, len(proxyURLs))
  29. for _, u := range proxyURLs {
  30. dialer, err := NewSocks5Dialer(newProxyDialer(baseDialer, u), u)
  31. if err != nil {
  32. return nil, fmt.Errorf("cannot build dialer for %s: %w", u.String(), err)
  33. }
  34. dialers = append(dialers, dialer)
  35. }
  36. return loadBalancedSocks5Dialer{
  37. dialers: dialers,
  38. }, nil
  39. }