-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpsock.go
74 lines (67 loc) · 1.34 KB
/
httpsock.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
package main
import (
"errors"
"net"
"strconv"
)
type httpsock struct {
IN *net.TCPConn
OUT *net.TCPConn
Buffer []byte
}
func newHttpSock(conn *net.TCPConn) *httpsock {
sock := httpsock{
IN: conn,
}
return &sock
}
func (sock *httpsock) Read(p []byte) (int, error) {
data := sock.Buffer
if data == nil {
line, _ := ReadLine(sock.IN) // skip until "\r\n"
// fmt.Println(line)
length, _ := strconv.ParseInt(line, 16, 32)
if length < 0 {
return 0, errors.New("strange length")
}
buffer := make([]byte, length)
for offset := int64(0); offset < length; {
n, err := sock.IN.Read(buffer[offset:])
if err != nil {
return 0, err
}
offset += int64(n)
}
data = buffer[:length]
line, err := ReadLine(sock.IN)
if err != nil {
return 0, err
}
// fmt.Println(line)
}
if len(data) <= len(p) {
for i := 0; i < len(data); i++ {
p[i] = data[i]
}
sock.Buffer = nil
return len(data), nil
}
for i := 0; i < len(p); i++ {
p[i] = data[i]
}
sock.Buffer = data[len(p):]
return len(p), nil
}
func (sock *httpsock) Write(b []byte) (int, error) {
// cLength := fmt.Sprintf("%x", len(b))
// fmt.Println(cLength)
// sock.IN.Write([]byte(cLength + "\n"))
// print(b)
return sock.IN.Write(b)
}
func (sock *httpsock) Close() error {
if sock.OUT != nil {
sock.OUT.Close()
}
return sock.IN.Close()
}