-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjsonrpc.go
More file actions
86 lines (75 loc) · 1.98 KB
/
jsonrpc.go
File metadata and controls
86 lines (75 loc) · 1.98 KB
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
package jsonrpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
)
// Client json rpc client
type Client struct {
// URL is remote url,
// example
// http://username:password@192.168.1.3:1001/jsonrpc
// ws://192.168.0.1:9121/
URL string
Transport Transport
}
type request struct {
Version string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID uint64 `json:"id"`
}
type response struct {
Version string `json:"jsonrpc"`
Result json.RawMessage `json:"result"`
Error *Error `json:"error"`
ID uint64 `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
// Error rpc error
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
func (e *Error) Error() string {
return fmt.Sprintf("code: %d, message: %s, data: %s",
e.Code, e.Message, e.Data)
}
// NewClient create a new jsonrpc client
func NewClient(uri string) (*Client, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
t := ""
switch u.Scheme {
case "http", "https":
t = "http"
case "ws", "wss":
t = "ws"
default:
return nil, fmt.Errorf("not supported %s", u.Scheme)
}
if t == "http" {
tr, _ := NewHTTPTransport(uri, nil)
return &Client{Transport: tr, URL: uri}, nil
}
if t == "ws" {
tr, _ := NewWebsocketTransport(context.Background(), uri)
return &Client{Transport: tr, URL: uri}, nil
}
return nil, errors.New("not supported")
}
// Call invoke a method with args and return reply
func (c *Client) Call(method string, args interface{}, reply interface{}) error {
return c.Transport.Call(method, args, reply)
}
// Subscribe subscribe for change
func (c *Client) Subscribe(method, notifyMethod string,
args interface{}, reply interface{}) (chan json.RawMessage, chan *Error, error) {
return c.Transport.Subscribe(method, notifyMethod, args, reply)
}