-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjrpc_test.go
104 lines (87 loc) · 2.17 KB
/
jrpc_test.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
package jrpc_test
import (
"context"
"encoding/json"
"fmt"
"net"
"testing"
"github.com/dalingng/jrpc"
)
type Main struct {
}
// 嵌套方法
func (m *Main)ChildrenMethods() ([]any, error){
return []any{
&Info{},
},nil
}
func (m *Main) Test(ctx context.Context, req struct {
Nickname *string
}) (string, error) {
if req.Nickname == nil {
return "", jrpc.NewError(10, "请填写用户名", nil)
}
return "你好:" + *req.Nickname, nil
}
type Info struct{
}
func (m *Info) Get(ctx context.Context)(string, error){
return "jrpc简单示例",nil
}
func Test(t *testing.T) {
jsonrpc := jrpc.JSONRPC{}
jsonrpc.Register(&Main{})
req := `[{"id":1,"jsonrpc":"2.0","method":"Main.Test","params":{}},{"id":2,"jsonrpc":"2.0","method":"Main.Test","params":{"Nickname":"大宁"}},{"id":3,"jsonrpc":"2.0","method":"Main.Info.Get","params":null}]`
t.Log("=========请求================")
t.Log("\n" + string(req))
res := jsonrpc.Call(context.Background(), []byte(req))
t.Log("=========返回结果================")
t.Log("\n" + string(res))
start := make(chan bool)
go func() {
listen, err := net.Listen("tcp", ":7890")
if err != nil {
t.Fatal(err.Error())
}
start <- true
for {
conn, err := listen.Accept()
if err != nil {
t.Fatal(err.Error())
}
enc := json.NewEncoder(conn)
dec := json.NewDecoder(conn)
for {
data := json.RawMessage{}
err := dec.Decode(&data)
if err != nil {
t.Fatal(err.Error())
}
res := jsonrpc.Call(context.Background(), data)
enc.Encode(json.RawMessage(res))
}
}
}()
// 等待socket服务器启动
<-start
t.Log("=========socket发送================")
conn, err := net.Dial("tcp", "127.0.0.1:7890")
if err != nil {
t.Fatal(err.Error())
}
enc := json.NewEncoder(conn)
dec := json.NewDecoder(conn)
reqData := jrpc.Request{
Id: json.RawMessage("1"),
Jsonrpc: json.RawMessage("2.0"),
Method: "Main.Test",
Params: json.RawMessage("null"),
}
t.Log("=========请求================")
t.Log(fmt.Sprintf("%+v", reqData))
enc.Encode(reqData)
r := json.RawMessage{}
dec.Decode(&r)
t.Log("=========返回结果================")
t.Log("\n" + string(r))
}