-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.go
102 lines (84 loc) · 2.02 KB
/
transport.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
package clefclient
import (
"bytes"
"encoding/json"
"errors"
"net"
"net/http"
)
// transport defines the interface for different transport mechanisms
type transport interface {
call(method string, params interface{}) (*rpcResponse, error)
close() error
}
// httpTransport implements transport interface for HTTP JSON-RPC
type httpTransport struct {
url string
}
func newHTTPTransport(url string) *httpTransport {
return &httpTransport{url: url}
}
func (t *httpTransport) call(method string, params interface{}) (*rpcResponse, error) {
reqBody, err := json.Marshal(rpcRequest{
Jsonrpc: "2.0",
Method: method,
Params: params,
ID: 1,
})
if err != nil {
return nil, err
}
resp, err := http.Post(t.url, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rpcResp rpcResponse
if err := json.NewDecoder(resp.Body).Decode(&rpcResp); err != nil {
return nil, err
}
if rpcResp.Error != nil {
return nil, errors.New(rpcResp.Error.Message)
}
return &rpcResp, nil
}
func (t *httpTransport) close() error {
return nil // HTTP transport doesn't need explicit cleanup
}
// ipcTransport implements transport interface for IPC
type ipcTransport struct {
conn net.Conn
}
func newIPCTransport(socketPath string) (*ipcTransport, error) {
conn, err := net.Dial("unix", socketPath)
if err != nil {
return nil, err
}
return &ipcTransport{conn: conn}, nil
}
func (t *ipcTransport) call(method string, params interface{}) (*rpcResponse, error) {
reqBody, err := json.Marshal(rpcRequest{
Jsonrpc: "2.0",
Method: method,
Params: params,
ID: 1,
})
if err != nil {
return nil, err
}
_, err = t.conn.Write(append(reqBody, '\n'))
if err != nil {
return nil, err
}
var rpcResp rpcResponse
if err := json.NewDecoder(t.conn).Decode(&rpcResp); err != nil {
return nil, err
}
if rpcResp.Error != nil {
return nil, errors.New(rpcResp.Error.Message)
}
return &rpcResp, nil
}
func (t *ipcTransport) close() error {
return t.conn.Close()
}