-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
68 lines (57 loc) · 1.18 KB
/
client.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
package http
import (
"fmt"
"io"
"strings"
)
// Client is an interface for the HTTP client.
type Client interface {
Do(req *Request) (*Response, error)
}
type client struct {
tcpClient TCPClient
dnsClient DNSClient
}
// NewClient returns a new HTTP client.
func NewClient() Client {
c := &client{
tcpClient: NewTCPClient(),
dnsClient: NewDNSClient(),
}
return c
}
// Do sends an HTTP request and returns an HTTP response as `io.ReadCloser`.
// The response should be closed.
func (c *client) Do(req *Request) (*Response, error) {
if req.Port == 0 {
req.Port = 80
}
ip, err := c.dnsClient.Resolve(req.Host)
if err != nil {
return nil, err
}
conn, err := c.tcpClient.Connect(ip, req.Port)
if err != nil {
return nil, err
}
defer conn.Close()
write(conn, req)
return parseResponse(conn)
}
func write(w io.Writer, req *Request) {
var header []string
for k, v := range req.Header {
header = append(header, fmt.Sprintf("%s: %s", k, v))
}
if req.Path == "" {
req.Path = "/"
}
const format = `%s %s HTTP/1.1
Host: %s:%d
%s
`
fmt.Fprintf(w, format, req.Method, req.Path, req.Host, req.Port, strings.Join(header, "\n"))
if req.Body != nil {
io.Copy(w, req.Body)
}
}