-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
121 lines (107 loc) · 2.53 KB
/
example.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
116
117
118
119
120
121
package main
import (
"context"
"errors"
"log"
"time"
"github.com/kroksys/jrpc/registry"
)
type Example struct{}
// {"jsonrpc":"2.0","method":"example.Simple", "id": 1, "params": [1, 2]}
func (Example) Simple(x, y int) (int, error) {
return x + y, nil
}
type simpleRequest struct {
X int
Y int
}
// {"jsonrpc":"2.0","method":"example.SimpleObject", "id": 1, "params": {"Y": 1, "x": 2}}
func (Example) SimpleObject(req simpleRequest) (int, error) {
log.Println("hello", req.X, req.Y)
return req.X + req.Y, nil
}
// {"jsonrpc":"2.0","method":"example.Simple", "id": 1}
func (Example) SimpleNoParams() (int, error) {
return 5, nil
}
func (Example) SimpleError() (int, error) {
return 0, errors.New("simple error")
}
// {"jsonrpc":"2.0","method":"example.Simple", "id": 1, "params": [1, 2]}
func (Example) SimpleWithContext(ctx context.Context, x, y int) (int, error) {
return x + y, nil
}
func (Example) Subscription(sub *registry.Subscription) error {
for i := 0; i < 10; i++ {
if !sub.IsRunning() {
break
}
if err := sub.Notify("Hello"); err != nil {
return err
}
time.Sleep(time.Second)
}
return nil
}
func (Example) SubscriptionWithContext(ctx context.Context, sub *registry.Subscription) error {
for i := 0; i < 10; i++ {
// <-sub.Exit and <-sub.Conn.Exit == !sub.IsRunning()
select {
case <-sub.Exit:
return nil
case <-sub.Conn.Exit:
return nil
default:
if err := sub.Notify("Hello"); err != nil {
return err
}
time.Sleep(time.Second)
}
}
return errors.New("expected subscription break")
}
func (Example) SubscriptionWithParams(
ctx context.Context,
sub *registry.Subscription,
req simpleRequest,
) error {
for i := 0; i < 10; i++ {
select {
case <-sub.Exit:
return nil
case <-sub.Conn.Exit:
return nil
default:
if err := sub.Notify("Hello"); err != nil {
return err
}
time.Sleep(time.Second)
}
}
return errors.New("expected subscription break")
}
func (Example) SubWithComplexStruct(
ctx context.Context,
sub *registry.Subscription,
req ComplexStruct,
) error {
for i := 0; i < 2; i++ {
select {
case <-sub.Exit:
return nil
case <-sub.Conn.Exit:
return nil
default:
if err := sub.Notify("Hello"); err != nil {
return err
}
time.Sleep(time.Second)
}
}
return errors.New("expected subscription break")
}
// !DONT DO THIS! - Params can havel only one struct passed so this will return error.
// Included only as an example.
func (Example) MultipleObject(req simpleRequest, multi int) (int, error) {
return (req.X + req.Y) * multi, nil
}