-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
51 lines (41 loc) · 934 Bytes
/
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
package redis_client
import (
"context"
"github.com/pkg/errors"
"io"
"net"
"time"
)
var (
_ io.Closer = &Client{}
)
type Client struct {
conn net.Conn
reader *Reader
writer *Writer
}
func (c *Client) Close() error {
return c.conn.Close()
}
func (c *Client) Send(values []interface{}) (*Result, error) {
c.conn.SetDeadline(time.Now().Add(time.Second * 5))
if err := c.writer.WriteArray(values); err != nil {
return nil, errors.Wrapf(err, "failed to execute operation: %v", values[0])
}
return c.reader.Read()
}
func Connect(ctx context.Context, address string) (*Client, error) {
dialer := net.Dialer{
Timeout: time.Second * 5,
KeepAlive: time.Second * 10,
}
conn, err := dialer.DialContext(ctx, "tcp4", address)
if err != nil {
return nil, errors.Wrapf(err, "failed to connect to %v", address)
}
return &Client{
conn: conn,
reader: NewReader(conn),
writer: NewWriter(conn),
}, nil
}