-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
238 lines (205 loc) · 5.75 KB
/
server.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Package searpc implements RPC framework for Seafile.
// It doesn't include transports, only provides function call and encode/decode.
//
/*
1. Defining a Service
type MyService struct {
}
func (s *MyService) Functioin1(a int, b string) *searpc.Result {
return nil
}
func (s *MyService) Function2(a string, b string, c int) *searpc.Result {
return nil
}
2. Registering a Service
svr := searpc.NewServer()
s := new(MyService)
svr.Register(s)
3. Calling a Service Function
jsonStr := transport.recv()
resStr := svr.Call("MyService", jsonStr)
*/
package searpc
import (
"encoding/json"
"errors"
"log"
"reflect"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
// service is a set of functions.
type service struct {
name string // name of service
rcvr reflect.Value // receiver of methods for the service
typ reflect.Type // type of the receiver
method map[string]*reflect.Method // registered methods
}
// Server represents an RPC Server.
type Server struct {
lock sync.RWMutex // protects the serviceMap
serviceMap map[string]*service
}
type Result struct {
Ret interface{} `json:"ret"`
ErrCode int `json:"err_code,omitempty"`
ErrMsg string `json:"err_msg,omitempty"`
}
var typeOfResult = reflect.TypeOf((*Result)(nil))
// NewServer returns a new Server.
func NewServer() *Server {
return &Server{serviceMap: make(map[string]*service)}
}
// Is this an exported - upper case - name?
func isExported(name string) bool {
rune, _ := utf8.DecodeRuneInString(name)
return unicode.IsUpper(rune)
}
func (server *Server) Register(rcvr interface{}, svcName string) error {
server.lock.Lock()
defer server.lock.Unlock()
if server.serviceMap == nil {
server.serviceMap = make(map[string]*service)
}
s := new(service)
s.typ = reflect.TypeOf(rcvr)
s.rcvr = reflect.ValueOf(rcvr)
sname := ""
if svcName != "" {
sname = svcName
} else {
sname := reflect.Indirect(s.rcvr).Type().Name()
if sname == "" {
s := "searpc.Register: no service name for type " + s.typ.String()
log.Print(s)
return errors.New(s)
}
if !isExported(sname) {
s := "searpc.Register: type " + sname + " is not exported"
log.Print(s)
return errors.New(s)
}
}
if _, present := server.serviceMap[sname]; present {
return errors.New("searpc: service already defined: " + sname)
}
s.name = sname
// Install the methods
s.method = suitableMethods(s.typ, true)
if len(s.method) == 0 {
str := ""
// To help the user, see if a pointer receiver would work.
method := suitableMethods(reflect.PtrTo(s.typ), false)
if len(method) != 0 {
str = "searpc.Register: type " + sname + " has no exported methods of suitable type (hint: pass a pointer to value of that type)"
} else {
str = "searpc.Register: type " + sname + " has no exported methods of suitable type"
}
log.Print(str)
return errors.New(str)
}
server.serviceMap[s.name] = s
return nil
}
// suitableMethods returns suitable Rpc methods of typ, it will report
// error using log if reportErr is true.
func suitableMethods(typ reflect.Type, reportErr bool) map[string]*reflect.Method {
methods := make(map[string]*reflect.Method)
for m := 0; m < typ.NumMethod(); m++ {
method := typ.Method(m)
mtype := method.Type
mname := strings.ToLower(method.Name)
// Method needs one out.
if mtype.NumOut() != 1 {
if reportErr {
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
}
continue
}
// The return type of the method must be Result.
if returnType := mtype.Out(0); returnType != typeOfResult {
if reportErr {
log.Println("method", mname, "returns", returnType.String(), "not Result")
}
continue
}
regMethod := method
methods[mname] = ®Method
}
return methods
}
const (
ServiceNotFoundError = 501
FunctionNotFoundError = 500
ParseJSONError = 511
ParameterError = 512
)
func (server *Server) Call(serviceName string, callStr []byte) (retStr []byte) {
var res *Result
var errStr string
var errCode int
service := server.serviceMap[serviceName]
if service == nil {
res = &Result{ErrCode: ServiceNotFoundError, ErrMsg: "Cannot find service " + serviceName}
retStr, _ = json.Marshal(*res)
return
}
var data interface{}
parseErr := json.Unmarshal(callStr, &data)
if parseErr != nil {
errStr = "Failed to parse call string:" + parseErr.Error()
errCode = ParseJSONError
log.Println(errStr)
res = &Result{ErrCode: errCode, ErrMsg: errStr}
retStr, _ = json.Marshal(*res)
return
}
array, ok := data.([]interface{})
if !ok || len(array) == 0 {
errStr = "Invalid call string format"
errCode = ParseJSONError
log.Println(errStr)
res = &Result{ErrCode: errCode, ErrMsg: errStr}
retStr, _ = json.Marshal(*res)
return
}
funcName, ok := array[0].(string)
if !ok {
errStr = "Invalid call string format"
errCode = ParseJSONError
log.Println(errStr)
res = &Result{ErrCode: errCode, ErrMsg: errStr}
retStr, _ = json.Marshal(*res)
return
}
funcName = strings.ToLower(funcName)
method := service.method[funcName]
if method == nil {
errStr = "Cannot find function " + funcName
errCode = FunctionNotFoundError
log.Println(errStr)
res = &Result{ErrCode: errCode, ErrMsg: errStr}
retStr, _ = json.Marshal(*res)
return
}
mtype := method.Type
// mtype.NumIn() includes the object itself
if mtype.NumIn() != len(array) {
errStr = "Parameters mismatch"
errCode = ParameterError
log.Println(errStr)
res = &Result{ErrCode: errCode, ErrMsg: errStr}
retStr, _ = json.Marshal(*res)
return
}
params := []reflect.Value{service.rcvr}
for i := 1; i < len(array); i++ {
params = append(params, reflect.ValueOf(array[i]))
}
errValue := method.Func.Call(params)
res = errValue[0].Interface().(*Result)
retStr, _ = json.Marshal(*res)
return
}