-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathnet.go
123 lines (110 loc) · 2.37 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package common
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
KiB = 1024
MiB = KiB * 1024
GiB = MiB * 1024
)
func HumanFriendlyTraffic(bytes uint64) string {
if bytes <= KiB {
return fmt.Sprintf("%d B", bytes)
}
if bytes <= MiB {
return fmt.Sprintf("%.2f KiB", float32(bytes)/KiB)
}
if bytes <= GiB {
return fmt.Sprintf("%.2f MiB", float32(bytes)/MiB)
}
return fmt.Sprintf("%.2f GiB", float32(bytes)/GiB)
}
func PickPort(network string, host string) int {
switch network {
case "tcp":
for retry := 0; retry < 16; retry++ {
l, err := net.Listen("tcp", host+":0")
if err != nil {
continue
}
defer l.Close()
_, port, err := net.SplitHostPort(l.Addr().String())
Must(err)
p, err := strconv.ParseInt(port, 10, 32)
Must(err)
return int(p)
}
case "udp":
for retry := 0; retry < 16; retry++ {
conn, err := net.ListenPacket("udp", host+":0")
if err != nil {
continue
}
defer conn.Close()
_, port, err := net.SplitHostPort(conn.LocalAddr().String())
Must(err)
p, err := strconv.ParseInt(port, 10, 32)
Must(err)
return int(p)
}
default:
return 0
}
return 0
}
func WriteAllBytes(writer io.Writer, payload []byte) error {
for len(payload) > 0 {
n, err := writer.Write(payload)
if err != nil {
return err
}
payload = payload[n:]
}
return nil
}
func WriteFile(path string, payload []byte) error {
writer, err := os.Create(path)
if err != nil {
return err
}
defer writer.Close()
return WriteAllBytes(writer, payload)
}
func FetchHTTPContent(target string) ([]byte, error) {
parsedTarget, err := url.Parse(target)
if err != nil {
return nil, fmt.Errorf("invalid URL: %s", target)
}
if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" {
return nil, fmt.Errorf("invalid scheme: %s", parsedTarget.Scheme)
}
client := &http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Do(&http.Request{
Method: "GET",
URL: parsedTarget,
Close: true,
})
if err != nil {
return nil, fmt.Errorf("failed to dial to %s", target)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected HTTP status code: %d", resp.StatusCode)
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read HTTP response")
}
return content, nil
}