/
http.go
118 lines (100 loc) · 2.29 KB
/
http.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
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
func main() {
get()
}
func get() {
url := "http://baidu.com/"
if len(os.Args) > 1 {
url = os.Args[1]
}
res, err := http.Get(url)
check_fail(err)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
check_fail(err)
fmt.Println(string(body))
}
func http_with_custom_header() {
req, err := http.NewRequest("GET", "http://www.baidu.com/", nil)
check_fail(err)
req.Header.Set("x-debug", "on")
resp, err := http.DefaultClient.Do(req)
check_fail(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
check_fail(err)
println(string(body))
}
// 参考: http://1234n.com/?post/mwsw2r
func http_with_timeout() {
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*1)
if err != nil {
return nil, err
}
return NewTimeoutConn(conn, time.Second*1), nil
},
ResponseHeaderTimeout: time.Second * 1,
},
}
req, err := http.NewRequest("GET", "http://www.google.com/", nil)
check_fail(err)
resp, err := client.Do(req)
check_fail(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
check_fail(err)
println(string(body))
}
type TimeoutConn struct {
conn net.Conn
timeout time.Duration
}
func NewTimeoutConn(conn net.Conn, timeout time.Duration) *TimeoutConn {
return &TimeoutConn{
conn: conn,
timeout: timeout,
}
}
func (c *TimeoutConn) Read(b []byte) (n int, err error) {
c.SetReadDeadline(time.Now().Add(c.timeout))
return c.conn.Read(b)
}
func (c *TimeoutConn) Write(b []byte) (n int, err error) {
c.SetWriteDeadline(time.Now().Add(c.timeout))
return c.conn.Write(b)
}
func (c *TimeoutConn) Close() error {
return c.conn.Close()
}
func (c *TimeoutConn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *TimeoutConn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *TimeoutConn) SetDeadline(t time.Time) error {
return c.conn.SetDeadline(t)
}
func (c *TimeoutConn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
func (c *TimeoutConn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
func check_fail(err error) {
if err != nil {
println(err)
os.Exit(1)
}
}