-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
59 lines (53 loc) · 1.31 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
package main
import (
"fmt"
"net/rpc"
"encoding/gob"
"bufio"
"time"
"net"
"io"
)
type gobClientCodec struct {
rwc io.ReadWriteCloser
dec *gob.Decoder
enc *gob.Encoder
encBuf *bufio.Writer
}
func (c *gobClientCodec) WriteRequest(r *rpc.Request, body interface{}) (err error) {
if err = TimeoutCoder(c.enc.Encode, r, "client write request"); err != nil {
return
}
if err = TimeoutCoder(c.enc.Encode, body, "client write request body"); err != nil {
return
}
return c.encBuf.Flush()
}
func (c *gobClientCodec) ReadResponseHeader(r *rpc.Response) error {
return c.dec.Decode(r)
}
func (c *gobClientCodec) ReadResponseBody(body interface{}) error {
return c.dec.Decode(body)
}
func (c *gobClientCodec) Close() error {
return c.rwc.Close()
}
func call(srv string, rpcname string, args interface{}, reply interface{}) error {
conn, err := net.DialTimeout("tcp", srv+":4200", time.Second*10)
if err != nil {
return fmt.Errorf("ConnectError: %s", err.Error())
}
encBuf := bufio.NewWriter(conn)
codec := &gobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf}
c := rpc.NewClientWithCodec(codec)
err = c.Call(rpcname, args, reply)
errc := c.Close()
if err != nil && errc != nil {
return fmt.Errorf("%s %s", err, errc)
}
if err != nil {
return err
} else {
return errc
}
}