-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadresponse.go
53 lines (49 loc) · 1.19 KB
/
readresponse.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
package main
import (
"bufio"
"errors"
"fmt"
"net"
"time"
)
func readResponseString(conn net.Conn) (string, error) {
var response string
// set SetReadDeadline
err := conn.SetReadDeadline(time.Now().Add(timeout))
if err != nil {
panic(fmt.Errorf("SetReadDeadline failed: %v", err))
}
response, err = bufio.NewReader(conn).ReadString('\n')
if err != nil {
var opErr *net.OpError
if errors.As(err, &opErr) {
if opErr.Timeout() {
return "", errors.New("no data (read timeout)")
}
return "", fmt.Errorf("read: %s", opErr.Err.Error())
}
return "", fmt.Errorf("read: %s", err.Error())
}
return response, nil
}
func readResponseBytes(conn net.Conn, len int) ([]byte, error) {
// set SetReadDeadline
err := conn.SetReadDeadline(time.Now().Add(timeout))
if err != nil {
panic(fmt.Errorf("SetReadDeadline failed: %v", err))
}
buf := make([]byte, len)
var l int
l, err = conn.Read(buf)
if err != nil {
var opErr *net.OpError
if errors.As(err, &opErr) {
if opErr.Timeout() {
return nil, errors.New("no data (read timeout)")
}
return nil, fmt.Errorf("read: %x", opErr.Err.Error())
}
return nil, fmt.Errorf("read: %s", err.Error())
}
return buf[:l], nil
}