github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/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  	"strings"
     9  )
    10  
    11  const (
    12  	// Remove the likelihood of errors by mistyping string values.
    13  	http_proxy  = "http_proxy"
    14  	https_proxy = "https_proxy"
    15  	ftp_proxy   = "ftp_proxy"
    16  	no_proxy    = "no_proxy"
    17  )
    18  
    19  // ProxySettings holds the values for the http, https and ftp proxies as well
    20  // as the no_proxy value found by Detect Proxies.
    21  type ProxySettings struct {
    22  	Http    string
    23  	Https   string
    24  	Ftp     string
    25  	NoProxy string
    26  }
    27  
    28  // DetectProxies returns the proxy settings found the environment.
    29  func DetectProxies() ProxySettings {
    30  	return ProxySettings{
    31  		Http:    getProxySetting(http_proxy),
    32  		Https:   getProxySetting(https_proxy),
    33  		Ftp:     getProxySetting(ftp_proxy),
    34  		NoProxy: getProxySetting(no_proxy),
    35  	}
    36  }
    37  
    38  // AsScriptEnvironment returns a potentially multi-line string in a format
    39  // that specifies exported key=value lines. There are two lines for each non-
    40  // empty proxy value, one lower-case and one upper-case.
    41  func (s *ProxySettings) AsScriptEnvironment() string {
    42  	lines := []string{}
    43  	addLine := func(proxy, value string) {
    44  		if value != "" {
    45  			lines = append(
    46  				lines,
    47  				fmt.Sprintf("export %s=%s", proxy, value),
    48  				fmt.Sprintf("export %s=%s", strings.ToUpper(proxy), value))
    49  		}
    50  	}
    51  	addLine(http_proxy, s.Http)
    52  	addLine(https_proxy, s.Https)
    53  	addLine(ftp_proxy, s.Ftp)
    54  	addLine(no_proxy, s.NoProxy)
    55  	return strings.Join(lines, "\n")
    56  }
    57  
    58  // AsEnvironmentValues returns a slice of strings of the format "key=value"
    59  // suitable to be used in a command environment. There are two values for each
    60  // non-empty proxy value, one lower-case and one upper-case.
    61  func (s *ProxySettings) AsEnvironmentValues() []string {
    62  	lines := []string{}
    63  	addLine := func(proxy, value string) {
    64  		if value != "" {
    65  			lines = append(
    66  				lines,
    67  				fmt.Sprintf("%s=%s", proxy, value),
    68  				fmt.Sprintf("%s=%s", strings.ToUpper(proxy), value))
    69  		}
    70  	}
    71  	addLine(http_proxy, s.Http)
    72  	addLine(https_proxy, s.Https)
    73  	addLine(ftp_proxy, s.Ftp)
    74  	addLine(no_proxy, s.NoProxy)
    75  	return lines
    76  }