-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponder.go
70 lines (59 loc) · 1.47 KB
/
responder.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
package jsonrpc
import (
"encoding/json"
"sync"
)
// Responder build Response message
type Responder struct {
request Request
proxy Proxy
}
// Respond build Response message with associated Request ID if provided
func (responder *Responder) Respond(result interface{}, err *Error) {
if err != nil {
result = nil
}
responder.proxy.Encode(Response{
ID: responder.request.ID,
Result: &Params{Value: result},
Error: err,
Version: SupportedVersion,
})
}
// SingleProxy encode one Response with JSON encoder
type SingleProxy struct {
encoder *json.Encoder
}
// Encode implements Proxy interface
func (proxy SingleProxy) Encode(response Response) {
proxy.encoder.Encode(response)
}
// NewBatchProxy creates new BatchProxy
func NewBatchProxy(encoder *json.Encoder) *BatchProxy {
return &BatchProxy{
guard: new(sync.Mutex),
processes: new(sync.WaitGroup),
encoder: encoder,
}
}
// BatchProxy encode all Response objects with JSON encoder
type BatchProxy struct {
guard *sync.Mutex
processes *sync.WaitGroup
responses []Response
encoder *json.Encoder
}
// Wait will wait all Response object to process
func (proxy *BatchProxy) Wait() {
proxy.processes.Wait()
if len(proxy.responses) > 0 {
proxy.encoder.Encode(proxy.responses)
}
}
// Encode implements Proxy interface
func (proxy *BatchProxy) Encode(response Response) {
proxy.guard.Lock()
defer proxy.guard.Unlock()
proxy.responses = append(proxy.responses, response)
proxy.processes.Done()
}