Skip to content

Commit

Permalink
improve proxy env parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
sagan committed Dec 27, 2023
1 parent 023106b commit 9fc1d9e
Showing 1 changed file with 7 additions and 35 deletions.
42 changes: 7 additions & 35 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -276,46 +277,17 @@ func First[T1 any, T2 any](v T1, args ...T2) T1 {
}

// Parse standard HTTP_PROXY, HTTPS_PROXY, NO_PROXY (and lowercase versions) envs, return proxy for urlStr.
// If urlStr is empty, return default http(s) proxy, prefer HTTPS_PROXY over HTTP_PROXY.
// However, it currently does not support CIDR style IP range value in NO_PROXY.
func ParseProxyFromEnv(urlStr string) string {
var noProxyEnv, httpProxyEnv, httpsProxyEnv string
if os.Getenv("NO_PROXY") != "" {
noProxyEnv = os.Getenv("NO_PROXY")
} else if os.Getenv("no_proxy") != "" {
noProxyEnv = os.Getenv("no_proxy")
}
if os.Getenv("HTTP_PROXY") != "" {
httpProxyEnv = os.Getenv("HTTP_PROXY")
} else if os.Getenv("http_proxy") != "" {
httpProxyEnv = os.Getenv("http_proxy")
}
if os.Getenv("HTTPS_PROXY") != "" {
httpsProxyEnv = os.Getenv("HTTPS_PROXY")
} else if os.Getenv("https_proxy") != "" {
httpsProxyEnv = os.Getenv("https_proxy")
}
if urlStr == "" {
if httpsProxyEnv != "" {
return httpsProxyEnv
}
return httpProxyEnv
return ""
}
urlObj, err := url.Parse(urlStr)
if err != nil {
if httpsProxyEnv != "" {
return httpsProxyEnv
}
return httpProxyEnv
}
if urlObj.Host != "" {
if noProxys := strings.Split(noProxyEnv, ","); slices.Index(noProxys, urlObj.Host) != -1 {
return ""
}
return ""
}
if urlObj.Scheme == "http" {
return httpProxyEnv
} else {
return httpsProxyEnv
proxyUrl, err := http.ProxyFromEnvironment(&http.Request{URL: urlObj})
if err != nil || proxyUrl == nil {
return ""
}
return proxyUrl.String()
}

0 comments on commit 9fc1d9e

Please sign in to comment.