github.com/argoproj/argo-cd/v3@v3.2.1/util/proxy/proxy.go (about)

     1  package proxy
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"os/exec"
     7  	"strings"
     8  
     9  	"golang.org/x/net/http/httpproxy"
    10  )
    11  
    12  // UpsertEnv removes the existing proxy env variables and adds the custom proxy variables
    13  func UpsertEnv(cmd *exec.Cmd, proxy string, noProxy string) []string {
    14  	envs := []string{}
    15  	if proxy == "" {
    16  		return cmd.Env
    17  	}
    18  	// remove the existing proxy env variable if present
    19  	for i, env := range cmd.Env {
    20  		proxyEnv := strings.ToLower(env)
    21  		if strings.HasPrefix(proxyEnv, "http_proxy") || strings.HasPrefix(proxyEnv, "https_proxy") || strings.HasPrefix(proxyEnv, "no_proxy") {
    22  			continue
    23  		}
    24  		envs = append(envs, cmd.Env[i])
    25  	}
    26  	return append(envs, httpProxy(proxy), httpsProxy(proxy), noProxyVar(noProxy))
    27  }
    28  
    29  // GetCallback returns the proxy callback function
    30  func GetCallback(proxy string, noProxy string) func(*http.Request) (*url.URL, error) {
    31  	if proxy != "" {
    32  		c := httpproxy.Config{
    33  			HTTPProxy:  proxy,
    34  			HTTPSProxy: proxy,
    35  			NoProxy:    noProxy,
    36  		}
    37  		return func(r *http.Request) (*url.URL, error) {
    38  			if r != nil {
    39  				return c.ProxyFunc()(r.URL)
    40  			}
    41  			return url.Parse(c.HTTPProxy)
    42  		}
    43  	}
    44  	// read proxy from env variable if custom proxy is missing
    45  	return http.ProxyFromEnvironment
    46  }
    47  
    48  func httpProxy(url string) string {
    49  	return "http_proxy=" + url
    50  }
    51  
    52  func httpsProxy(url string) string {
    53  	return "https_proxy=" + url
    54  }
    55  
    56  func noProxyVar(noProxy string) string {
    57  	return "no_proxy=" + noProxy
    58  }