-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck.go
66 lines (53 loc) · 1.52 KB
/
check.go
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
package main
import (
"context"
"log"
"net/http"
"net/url"
"time"
)
func checkProxy(proxyString string, urlString string) (bool, int) {
proxyUrl := parseProxyURL(proxyString)
client := createNewHTTPClient(proxyUrl)
// Create the HTTP GET request
req, err := http.NewRequest("GET", urlString, nil)
if err != nil {
log.Printf("Failed to create HTTP GET request: %s", err)
}
// Set timeout
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
timestampStart := time.Now().UnixNano() / int64(time.Millisecond) // Start request
// Send the request
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
log.Printf("HTTP GET request failed: %s", err)
return false, 0
}
defer resp.Body.Close()
timestampFinish := time.Now().UnixNano() / int64(time.Millisecond) // End request
timeDiff := timestampFinish - timestampStart // Calc diff
if resp.StatusCode != 418 {
return false, int(timeDiff)
}
return true, int(timeDiff)
}
// Returns a URL object when given a string
func parseProxyURL(proxyString string) *url.URL {
proxyUrl, err := url.Parse("http://" + proxyString)
if err != nil {
log.Printf("Invalid proxy URL: %s", err)
}
return proxyUrl
}
// Returns a custom HTTP client
func createNewHTTPClient(proxyUrl *url.URL) *http.Client {
// Apply transport settings
tr := &http.Transport{
DisableKeepAlives: true,
Proxy: http.ProxyURL(proxyUrl),
ProxyConnectHeader: http.Header{},
}
client := &http.Client{Transport: tr}
return client
}