forked from egirna/icap-client
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransport.go
More file actions
123 lines (94 loc) · 2.43 KB
/
transport.go
File metadata and controls
123 lines (94 loc) · 2.43 KB
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 icapclient
import (
"context"
"io"
"net"
"strings"
"time"
)
// transport represents the transport layer data
type transport struct {
network string
addr string
timeout time.Duration
readTimeout time.Duration
writeTimeout time.Duration
sckt net.Conn
}
// dial fires up a tcp socket
func (t *transport) dial() error {
sckt, err := net.DialTimeout(t.network, t.addr, t.timeout)
if err != nil {
return err
}
if err := sckt.SetReadDeadline(time.Now().UTC().Add(t.readTimeout)); err != nil {
return err
}
if err := sckt.SetWriteDeadline(time.Now().UTC().Add(t.writeTimeout)); err != nil {
return err
}
t.sckt = sckt
return nil
}
// dialWithContext fires up a tcp socket
func (t *transport) dialWithContext(ctx context.Context) error {
sckt, err := (&net.Dialer{
Timeout: t.timeout,
}).DialContext(ctx, t.network, t.addr)
if err != nil {
return err
}
if err := sckt.SetReadDeadline(time.Now().UTC().Add(t.readTimeout)); err != nil {
return err
}
if err := sckt.SetWriteDeadline(time.Now().UTC().Add(t.writeTimeout)); err != nil {
return err
}
t.sckt = sckt
return nil
}
// Write writes data to the server
func (t *transport) write(data []byte) (int, error) {
logDebug("Dumping the message being sent to the server...")
dumpDebug(string(data))
return t.sckt.Write(data)
}
// Read reads data from server
func (t *transport) read() (string, error) {
data := make([]byte, 0)
logDebug("Dumping messages received from the server...")
for {
tmp := make([]byte, 1096)
n, err := t.sckt.Read(tmp)
if err != nil {
if err == io.EOF {
logDebug("End of file detected from EOF error")
break
}
return "", err
}
if n == 0 {
logDebug("End of file detected by 0 bytes")
break
}
data = append(data, tmp[:n]...)
if string(data) == icap100ContinueMsg { // explicitly breaking because the Read blocks for 100 continue message // TODO: find out why
logDebug("Stopping because got 100 Continue from the server")
break
}
if strings.HasSuffix(string(data), "0\r\n\r\n") {
logDebug("End of the file detected by 0 Double CRLF indicator")
break
}
if strings.Contains(string(data), icap204NoModsMsg) {
logDebug("End of file detected by 204 no modifications and Double CRLF at the end")
break
}
dumpDebug(string(tmp))
}
return string(data), nil
}
// close closes the tcp connection
func (t *transport) close() error {
return t.sckt.Close()
}