proxy.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sockets
  2. import (
  3. "net"
  4. "net/url"
  5. "os"
  6. "strings"
  7. "golang.org/x/net/proxy"
  8. )
  9. // GetProxyEnv allows access to the uppercase and the lowercase forms of
  10. // proxy-related variables. See the Go specification for details on these
  11. // variables. https://golang.org/pkg/net/http/
  12. func GetProxyEnv(key string) string {
  13. proxyValue := os.Getenv(strings.ToUpper(key))
  14. if proxyValue == "" {
  15. return os.Getenv(strings.ToLower(key))
  16. }
  17. return proxyValue
  18. }
  19. // DialerFromEnvironment takes in a "direct" *net.Dialer and returns a
  20. // proxy.Dialer which will route the connections through the proxy using the
  21. // given dialer.
  22. func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) {
  23. allProxy := GetProxyEnv("all_proxy")
  24. if len(allProxy) == 0 {
  25. return direct, nil
  26. }
  27. proxyURL, err := url.Parse(allProxy)
  28. if err != nil {
  29. return direct, err
  30. }
  31. proxyFromURL, err := proxy.FromURL(proxyURL, direct)
  32. if err != nil {
  33. return direct, err
  34. }
  35. noProxy := GetProxyEnv("no_proxy")
  36. if len(noProxy) == 0 {
  37. return proxyFromURL, nil
  38. }
  39. perHost := proxy.NewPerHost(proxyFromURL, direct)
  40. perHost.AddFromString(noProxy)
  41. return perHost, nil
  42. }