-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
87 lines (77 loc) · 1.67 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
package main
import (
"errors"
"fmt"
"log"
"net"
)
type Client struct {
elements []*Element
conn net.Conn
}
func NewClient(socket string) (*Client, error) {
c := new(Client)
if err := c.Open(socket); err != nil {
return nil, err
}
return c, nil
}
func (c *Client) Open(socket string) error {
conn, err := net.Dial("unix", socket)
if err != nil {
log.Printf("error: %v\n", err)
return err
}
c.conn = conn
return nil
}
func (c *Client) Set(name string, key []byte) error {
c.addData([]byte("set"))
c.addData([]byte(name))
c.addData(key)
return nil
}
func (c *Client) GetHash(name string) error {
c.addData([]byte("getHash"))
c.addData([]byte(name))
return nil
}
func (c *Client) Encrypt(name string, plaintext []byte) error {
c.addData([]byte("encrypt"))
c.addData([]byte(name))
c.addData(plaintext)
return nil
}
func (c *Client) Decrypt(name string, ciphertext []byte) error {
c.addData([]byte("decrypt"))
c.addData([]byte(name))
c.addData(ciphertext)
return nil
}
func (c *Client) Send() ([]byte, error) {
req := NewResult()
if req.SetMultiple(c.elements) {
_, err := c.conn.Write(req.data)
if err != nil {
return nil, err
}
err = c.conn.(*net.UnixConn).CloseWrite()
if err != nil {
return nil, err
}
parser := NewParser()
if err := parser.Parse(c.conn); err != nil {
return nil, err
}
element := parser.elements[0]
if element.kind == ERROR_STRING {
return nil, fmt.Errorf("ERROR: %v", string(parser.elements[0].data))
}
return parser.elements[0].data, nil
}
return nil, errors.New("unknown error")
}
func (c *Client) addData(data []byte) error {
c.elements = append(c.elements, NewElement(len(data), data))
return nil
}