/
rpc.go
88 lines (77 loc) · 1.89 KB
/
rpc.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
package appserver
import (
"github.com/eaciit/toolkit"
//"time"
"errors"
"strings"
)
//type RpcFn func(toolkit.M, *toolkit.Result) error
type RpcFn func(toolkit.M) *toolkit.Result
type RpcFns map[string]*RpcFnInfo
type RpcFnInfo struct {
AuthRequired bool
AuthType string
Fn RpcFn
}
//type ReturnedBytes []byte
type Rpc struct {
Fns RpcFns
Server *Server
MarshallingMethod string
}
var _marshallingMethod string
func MarshallingMethod() string {
if _marshallingMethod == "" {
_marshallingMethod = "gob"
} else {
_marshallingMethod = strings.ToLower(_marshallingMethod)
}
return _marshallingMethod
}
func SetMarshallingMethod(m string) {
_marshallingMethod = m
}
func (r *Rpc) Do(in toolkit.M, out *toolkit.Result) error {
if r.Fns == nil {
r.Fns = map[string]*RpcFnInfo{}
}
in.Set("rpc", r)
method := in.GetString("method")
if method == "" {
return errors.New("Method is empty")
}
fninfo, fnExist := r.Fns[method]
if !fnExist {
return errors.New("Method " + method + " is not exist")
}
if fninfo.AuthRequired {
referenceID := in.GetString("auth_referenceid")
secret := in.GetString("auth_secret")
valid := r.Server.validateSecret(fninfo.AuthType, referenceID, secret)
if !valid {
return errors.New("Unauthorised to call " + method)
}
}
res := fninfo.Fn(in)
if res.Status != toolkit.Status_OK {
return errors.New("RPC Call error: " + res.Message)
}
//*out = toolkit.ToBytes(res.Data, MarshallingMethod())
*out = *res
return nil
}
func AddFntoRpc(r *Rpc, svr *Server, k string, fn RpcFn, needValidation bool, authType string) {
//func (r *Rpc) AddFn(k string, fn RpcFn) {
//if r.Server == nil {
svr.Log.Info("Register " + svr.Address + "/" + k)
r.Server = svr
//}
if r.Fns == nil {
r.Fns = map[string]*RpcFnInfo{}
}
r.Fns[k] = &RpcFnInfo{
AuthRequired: needValidation,
AuthType: authType,
Fn: fn,
}
}