-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
123 lines (98 loc) · 2.16 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
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 client
import (
"context"
"fmt"
"net"
"github.com/MSSkowron/MSCache/internal/protocol"
)
// Client is a client for the cache server.
type Client struct {
conn net.Conn
}
// New creates a new client.
func New(endpoint string) (*Client, error) {
conn, err := net.Dial("tcp", endpoint)
if err != nil {
return nil, err
}
return &Client{
conn: conn,
}, nil
}
// Close closes the connection.
func (c *Client) Close() error {
return c.conn.Close()
}
// Get sends a get command to the server.
func (c *Client) Get(ctx context.Context, key []byte) ([]byte, error) {
cmd := &protocol.CommandGet{
Key: key,
}
b, err := cmd.Bytes()
if err != nil {
return nil, err
}
_, err = c.conn.Write(b)
if err != nil {
return nil, err
}
resp, err := protocol.ParseGetResponse(c.conn)
if err != nil {
return nil, err
}
if resp.Status != protocol.StatusOK {
return nil, fmt.Errorf("server responded with non OK status [%s]", resp.Status)
}
return resp.Value, nil
}
// Set sends a set command to the server.
// ttl is in seconds.
func (c *Client) Set(ctx context.Context, key, value []byte, ttl int) error {
cmd := &protocol.CommandSet{
Key: key,
Value: value,
TTL: ttl,
}
b, err := cmd.Bytes()
if err != nil {
return err
}
_, err = c.conn.Write(b)
if err != nil {
return err
}
resp, err := protocol.ParseSetResponse(c.conn)
if err != nil {
return err
}
if resp.Status != protocol.StatusOK {
return fmt.Errorf("server responded with non OK status [%s]", resp.Status)
}
return nil
}
// Delete sends a delete command to the server.
func (c *Client) Delete(ctx context.Context, key []byte) error {
cmd := &protocol.CommandDelete{
Key: key,
}
b, err := cmd.Bytes()
if err != nil {
return err
}
_, err = c.conn.Write(b)
if err != nil {
return err
}
resp, err := protocol.ParseDeleteResponse(c.conn)
if err != nil {
return err
}
if resp.Status != protocol.StatusOK {
return fmt.Errorf("server responded with non OK status [%s]", resp.Status)
}
return nil
}
// String returns the string representation of the client which is the client's address.
func (c Client) String() string {
return c.conn.RemoteAddr().String()
}