-
Notifications
You must be signed in to change notification settings - Fork 35
/
net.go
62 lines (55 loc) · 1.24 KB
/
net.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
package build
import (
"fmt"
"net"
"net/http"
"sync"
"time"
)
const httpUserAgent = "zonedb/1.0 (https://github.com/zonedb/zonedb)"
var (
// Concurrency specifies the maximimum number of concurrent build operations to execute.
Concurrency = 32
// Timeout specifies the maximum duration to wait for network operations to complete.
Timeout = 10 * time.Second
)
// Fetch fetches a URL.
func Fetch(u string) (*http.Response, error) {
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", httpUserAgent)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP error for %s: %s", u, res.Status)
}
return res, nil
}
// CanDial verifies if possible to connect to a given network and address.
// Returns nil for successful dial or an error.
func CanDial(network, addr string) error {
var k = network + " " + addr
mtx.RLock()
err, ok := dialCache[k]
mtx.RUnlock()
if ok {
return err
}
c, err := net.DialTimeout(network, addr, Timeout)
mtx.Lock()
dialCache[k] = err
mtx.Unlock()
if err != nil {
return err
}
c.Close()
return nil
}
var (
dialCache = make(map[string]error)
mtx sync.RWMutex
)