/
client.go
115 lines (93 loc) · 2.61 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
// Copyright 2016 polaris. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// http://studygolang.com
// Author:polaris polaris@studygolang.com
package luna
import (
"net"
"net/rpc"
"net/rpc/jsonrpc"
"time"
"github.com/ugorji/go/codec"
)
type Client struct {
*rpc.Client
encodingType uint8
}
func NewDefaultClient() *Client {
return &Client{}
}
func NewClientWithEncoding(encodingType uint8) *Client {
return &Client{
encodingType: encodingType,
}
}
func Dial(network, address string, encodingType uint8) (*Client, error) {
client := NewClientWithEncoding(encodingType)
err := client.Dial(network, address)
return client, err
}
func DialTCP(address string, encodingType uint8) (*Client, error) {
return Dial("tcp", address, encodingType)
}
// func DialHTTP(address string, encodingType uint8) (*Client, error) {
// client := NewClientWithEncoding(encodingType)
// var err error
// conn, err := net.Dial("tcp", address)
// if err != nil {
// return nil, err
// }
// io.WriteString(conn, "CONNECT "+RpcPathMap[encodingType]+" HTTP/1.0\n\n")
// // Require successful HTTP response
// // before switching to RPC protocol.
// resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
// if err == nil && resp.Status == connected {
// client.fillRpcClient(conn)
// return client, nil
// }
// if err == nil {
// err = errors.New("unexpected HTTP response: " + resp.Status)
// }
// conn.Close()
// return nil, &net.OpError{
// Op: "dial-http",
// Net: "tcp " + address,
// Addr: nil,
// Err: err,
// }
// }
func DialTimeout(address string, encodingType uint8, timeout time.Duration) (*Client, error) {
client := NewClientWithEncoding(encodingType)
err := client.DialTimeout("tcp", address, timeout)
return client, err
}
func (c *Client) Dial(network, address string) error {
conn, err := net.Dial(network, address)
if err != nil {
return err
}
c.fillRpcClient(conn)
return nil
}
func (c *Client) DialTimeout(network, address string, timeout time.Duration) error {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return err
}
c.fillRpcClient(conn)
return nil
}
func (c *Client) fillRpcClient(conn net.Conn) {
switch c.encodingType {
case EncodingTypeJson:
c.Client = jsonrpc.NewClient(conn)
case EncodingTypeMsgpack:
rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, new(codec.MsgpackHandle))
c.Client = rpc.NewClientWithCodec(rpcCodec)
case EncodingTypeGob:
c.Client = rpc.NewClient(conn)
default:
c.Client = jsonrpc.NewClient(conn)
}
}