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