-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.go
54 lines (46 loc) · 1.1 KB
/
pipe.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
package fork
import "fmt"
type ServerPipe struct {
serverTransport ServerTransport
marshaller Marshaller
}
type ClientPipe struct {
clientTransport ClientTransport
marshaller Marshaller
}
func RegisterHandler[In any, Out any](p *ServerPipe, fun string, handler func(in In) (out Out, err error)) {
p.serverTransport.Register(fun, func(in []byte) ([]byte, error) {
input := new(In)
err := p.marshaller.Decode(in, input)
if err != nil {
return nil, err
}
out, err := handler(*input)
if err != nil {
return nil, err
}
return p.marshaller.Encode(out)
})
}
func Call(p *ClientPipe, fun string, in interface{}, out interface{}) error {
if p == nil {
return fmt.Errorf("client pipe is nil ,may not ready")
}
input, err := p.marshaller.Encode(in)
if err != nil {
return err
}
output, err := p.clientTransport.Call(fun, input)
if err != nil {
return err
}
return p.marshaller.Decode(output, out)
}
func CallR[R any](p *ClientPipe, fun string, in interface{}) (r R, err error) {
out := new(R)
err = Call(p, fun, in, out)
if err != nil {
return
}
return *out, nil
}