launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/juju/osenv/proxy.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package osenv 5 6 import ( 7 "fmt" 8 "os" 9 "strings" 10 ) 11 12 const ( 13 // Remove the likelihood of errors by mistyping string values. 14 http_proxy = "http_proxy" 15 https_proxy = "https_proxy" 16 ftp_proxy = "ftp_proxy" 17 ) 18 19 // ProxySettings holds the values for the http, https and ftp proxies found by 20 // Detect Proxies. 21 type ProxySettings struct { 22 Http string 23 Https string 24 Ftp string 25 } 26 27 func getProxySetting(key string) string { 28 value := os.Getenv(key) 29 if value == "" { 30 value = os.Getenv(strings.ToUpper(key)) 31 } 32 return value 33 } 34 35 // DetectProxies returns the proxy settings found the environment. 36 func DetectProxies() ProxySettings { 37 return ProxySettings{ 38 Http: getProxySetting(http_proxy), 39 Https: getProxySetting(https_proxy), 40 Ftp: getProxySetting(ftp_proxy), 41 } 42 } 43 44 // AsScriptEnvironment returns a potentially multi-line string in a format 45 // that specifies exported key=value lines. There are two lines for each non- 46 // empty proxy value, one lower-case and one upper-case. 47 func (s *ProxySettings) AsScriptEnvironment() string { 48 lines := []string{} 49 addLine := func(proxy, value string) { 50 if value != "" { 51 lines = append( 52 lines, 53 fmt.Sprintf("export %s=%s", proxy, value), 54 fmt.Sprintf("export %s=%s", strings.ToUpper(proxy), value)) 55 } 56 } 57 addLine(http_proxy, s.Http) 58 addLine(https_proxy, s.Https) 59 addLine(ftp_proxy, s.Ftp) 60 return strings.Join(lines, "\n") 61 } 62 63 // AsEnvironmentValues returns a slice of strings of the format "key=value" 64 // suitable to be used in a command environment. There are two values for each 65 // non-empty proxy value, one lower-case and one upper-case. 66 func (s *ProxySettings) AsEnvironmentValues() []string { 67 lines := []string{} 68 addLine := func(proxy, value string) { 69 if value != "" { 70 lines = append( 71 lines, 72 fmt.Sprintf("%s=%s", proxy, value), 73 fmt.Sprintf("%s=%s", strings.ToUpper(proxy), value)) 74 } 75 } 76 addLine(http_proxy, s.Http) 77 addLine(https_proxy, s.Https) 78 addLine(ftp_proxy, s.Ftp) 79 return lines 80 } 81 82 // SetEnvironmentValues updates the process environment with the 83 // proxy values stored in the settings object. Both the lower-case 84 // and upper-case variants are set. 85 // 86 // http_proxy, HTTP_PROXY 87 // https_proxy, HTTPS_PROXY 88 // ftp_proxy, FTP_PROXY 89 func (s *ProxySettings) SetEnvironmentValues() { 90 setenv := func(proxy, value string) { 91 os.Setenv(proxy, value) 92 os.Setenv(strings.ToUpper(proxy), value) 93 } 94 setenv(http_proxy, s.Http) 95 setenv(https_proxy, s.Https) 96 setenv(ftp_proxy, s.Ftp) 97 }