Skip to content

Commit 3d09577

Browse files
committed
Switches to not creating new http client for every request
1 parent f77b38d commit 3d09577

File tree

1 file changed

+27
-17
lines changed

1 file changed

+27
-17
lines changed

main.go

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,31 @@ func main() {
4141
var to int
4242
flag.IntVar(&to, "t", 10000, "timeout (milliseconds)")
4343

44+
// verbose flag
45+
var verbose bool
46+
flag.BoolVar(&verbose, "v", false, "output errors to stderr")
47+
4448
flag.Parse()
4549

4650
// make an actual time.Duration out of the timeout
4751
timeout := time.Duration(to * 1000000)
4852

53+
var tr = &http.Transport{
54+
MaxIdleConns: 30,
55+
IdleConnTimeout: time.Second,
56+
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
57+
}
58+
59+
re := func(req *http.Request, via []*http.Request) error {
60+
return http.ErrUseLastResponse
61+
}
62+
63+
client := &http.Client{
64+
Transport: tr,
65+
CheckRedirect: re,
66+
Timeout: timeout,
67+
}
68+
4969
// we send urls to check on the urls channel,
5070
// but only get them on the output channel if
5171
// they are accepting connections
@@ -58,8 +78,13 @@ func main() {
5878

5979
go func() {
6080
for url := range urls {
61-
if isListening(url, timeout) {
81+
if isListening(client, url) {
6282
fmt.Println(url)
83+
continue
84+
}
85+
86+
if verbose {
87+
fmt.Fprintf(os.Stderr, "failed: %s\n", url)
6388
}
6489
}
6590

@@ -103,22 +128,7 @@ func main() {
103128
wg.Wait()
104129
}
105130

106-
func isListening(url string, timeout time.Duration) bool {
107-
var tr = &http.Transport{
108-
MaxIdleConns: 30,
109-
IdleConnTimeout: time.Second * 30,
110-
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
111-
}
112-
113-
re := func(req *http.Request, via []*http.Request) error {
114-
return http.ErrUseLastResponse
115-
}
116-
117-
client := &http.Client{
118-
Transport: tr,
119-
CheckRedirect: re,
120-
Timeout: timeout,
121-
}
131+
func isListening(client *http.Client, url string) bool {
122132

123133
req, err := http.NewRequest("GET", url, nil)
124134
if err != nil {

0 commit comments

Comments
 (0)