forked from tomnomnom/gron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.go
More file actions
97 lines (84 loc) · 2.13 KB
/
Copy pathurl.go
File metadata and controls
97 lines (84 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"bufio"
"crypto/tls"
"fmt"
"io"
"net/http"
neturl "net/url"
"os"
"regexp"
"strings"
"time"
)
func validURL(url string) bool {
r := regexp.MustCompile("(?i)^http(?:s)?://")
return r.MatchString(url)
}
func configureProxy(url string, proxy string, noProxy string) func(*http.Request) (*neturl.URL, error) {
cURL, err := neturl.Parse(url)
if err != nil {
return nil
}
// Direct arguments are superior to environment variables.
if proxy == undefinedProxy {
proxy = os.Getenv(fmt.Sprintf("%s_proxy", cURL.Scheme))
}
if noProxy == undefinedProxy {
noProxy = os.Getenv("no_proxy")
}
// Skip setting a proxy if no proxy has been set through env variable or
// argument.
if proxy == "" {
return nil
}
// Test if any of the hosts mentioned in the noProxy variable or the
// no_proxy env variable. Skip setting up the proxy if a match is found.
noProxyHosts := strings.Split(noProxy, ",")
if len(noProxyHosts) > 0 {
for _, noProxyHost := range noProxyHosts {
if len(noProxyHost) == 0 {
continue
}
// Test for direct matches of the hostname.
if cURL.Host == noProxyHost {
return nil
}
// Match through wildcard-like pattern, e.g. ".foobar.com" should
// match all subdomains of foobar.com.
if strings.HasPrefix(noProxyHost, ".") && strings.HasSuffix(cURL.Host, noProxyHost) {
return nil
}
}
}
proxyURL, err := neturl.Parse(proxy)
if err != nil {
return nil
}
return http.ProxyURL(proxyURL)
}
func getURL(url string, insecure bool, proxyURL string, noProxy string) (io.Reader, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure},
}
// Set proxy if defined.
proxy := configureProxy(url, proxyURL, noProxy)
if proxy != nil {
tr.Proxy = proxy
}
client := http.Client{
Transport: tr,
Timeout: 20 * time.Second,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", fmt.Sprintf("gron/%s", gronVersion))
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return bufio.NewReader(resp.Body), err
}