-
Notifications
You must be signed in to change notification settings - Fork 0
/
reflect.go
430 lines (371 loc) · 13.5 KB
/
reflect.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//Copyright 2011 Siyabonga Dlamini ([email protected]). All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
//OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
//OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package gorest
import (
"bytes"
"io"
"log"
"net/http"
"reflect"
"strings"
)
const (
ERROR_INVALID_INTERFACE = "RegisterService(interface{}) takes a pointer to a struct that inherits from type RestService. Example usage: gorest.RegisterService(new(ServiceOne)) "
)
//Bootstrap functions below
//------------------------------------------------------------------------------------------
//Takes a value of a struct representing a service.
func registerService(root string, h interface{}) {
if _, ok := h.(GoRestService); !ok {
panic(ERROR_INVALID_INTERFACE)
}
t := reflect.TypeOf(h)
if t.Kind() == reflect.Ptr {
t = t.Elem()
} else {
panic(ERROR_INVALID_INTERFACE)
}
if t.Kind() == reflect.Struct {
if field, found := t.FieldByName("RestService"); found {
temp := strings.Join(strings.Fields(string(field.Tag)), " ")
meta := prepServiceMetaData(root, reflect.StructTag(temp), h, t.Name())
tFullName := _manager().addType(t.PkgPath()+"/"+t.Name(), meta)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
mapFieldsToMethods(t, f, tFullName, meta.root)
}
}
return
}
panic(ERROR_INVALID_INTERFACE)
}
func mapFieldsToMethods(t reflect.Type, f reflect.StructField, typeFullName string, serviceRoot string) {
if f.Name != "RestService" && f.Type.Name() == "EndPoint" { //TODO: Proper type checking, not by name
temp := strings.Join(strings.Fields(string(f.Tag)), " ")
ep := makeEndPointStruct(reflect.StructTag(temp), serviceRoot)
ep.parentTypeName = typeFullName
ep.name = f.Name
var method reflect.Method
methodName := strings.ToUpper(f.Name[:1]) + f.Name[1:]
methFound := false
methodNumberInParent := 0
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
if methodName == m.Name {
method = m //As long as the name is the same, we know we have found the method, since go has no overloading
methFound = true
methodNumberInParent = i
break
}
}
{ //Panic Checks
if !methFound {
log.Panic("Method name not found. " + panicMethNotFound(methFound, ep, t, f, methodName))
}
if !isLegalForRequestType(method.Type, ep) {
log.Panic("Parameter list not matching. " + panicMethNotFound(methFound, ep, t, f, methodName))
}
}
ep.methodNumberInParent = methodNumberInParent
_manager().addEndPoint(ep)
log.Println("Registerd service:", t.Name(), " endpoint:", ep.requestMethod, ep.signiture)
}
}
func isLegalForRequestType(methType reflect.Type, ep endPointStruct) (cool bool) {
cool = true
numInputIgnore := 0
numOut := 0
switch ep.requestMethod {
case POST, PUT, PATCH:
{
numInputIgnore = 2 //The first param is the struct, the second the posted object
numOut = 0
}
case GET:
{
numInputIgnore = 1 //The first param is the default service struct
numOut = 1
}
case DELETE, HEAD, OPTIONS:
{
numInputIgnore = 1 //The first param is the default service struct
numOut = 0
}
}
if (methType.NumIn() - numInputIgnore) != (ep.paramLen + len(ep.queryParams)) {
cool = false
} else if methType.NumOut() != numOut {
cool = false
} else {
//Check the first parameter type for POST and PUT
if numInputIgnore == 2 {
methVal := methType.In(1)
if ep.postdataTypeIsArray {
if methVal.Kind() == reflect.Slice {
methVal = methVal.Elem()
} else {
cool = false
return
}
}
if ep.postdataTypeIsMap {
if methVal.Kind() == reflect.Map {
methVal = methVal.Elem()
} else {
cool = false
return
}
}
if !typeNamesEqual(methVal, ep.postdataType) {
cool = false
return
}
}
//Check the rest of input path param types
i := numInputIgnore
if ep.isVariableLength {
if methType.NumIn() != numInputIgnore+1+len(ep.queryParams) {
cool = false
}
cool = false
if methType.In(i).Kind() == reflect.Slice { //Variable args Slice
if typeNamesEqual(methType.In(i).Elem(), ep.params[0].typeName) { //Check the correct type for the Slice
cool = true
}
}
} else {
for ; i < methType.NumIn() && (i-numInputIgnore < ep.paramLen); i++ {
if !typeNamesEqual(methType.In(i), ep.params[i-numInputIgnore].typeName) {
cool = false
break
}
}
}
//Check the input Query param types
for j := 0; i < methType.NumIn() && (j < len(ep.queryParams)); i++ {
if !typeNamesEqual(methType.In(i), ep.queryParams[j].typeName) {
cool = false
break
}
j++
}
//Check output param type.
if numOut == 1 {
methVal := methType.Out(0)
if ep.outputTypeIsArray {
if methVal.Kind() == reflect.Slice {
methVal = methVal.Elem() //Only convert if it is mentioned as a slice in the tags, otherwise allow for failure panic
} else {
cool = false
return
}
}
if ep.outputTypeIsMap {
if methVal.Kind() == reflect.Map {
methVal = methVal.Elem()
} else {
cool = false
return
}
}
if !typeNamesEqual(methVal, ep.outputType) {
cool = false
}
}
}
return
}
func typeNamesEqual(methVal reflect.Type, name2 string) bool {
if strings.Index(name2, ".") == -1 {
return methVal.Name() == name2
}
fullName := strings.Replace(methVal.PkgPath(), "/", ".", -1) + "." + methVal.Name()
return fullName == name2
}
func panicMethNotFound(methFound bool, ep endPointStruct, t reflect.Type, f reflect.StructField, methodName string) string {
var str string
isArr := ""
postIsArr := ""
if ep.outputTypeIsArray {
isArr = "[]"
}
if ep.outputTypeIsMap {
isArr = "map[string]"
}
if ep.postdataTypeIsArray {
postIsArr = "[]"
}
if ep.postdataTypeIsMap {
postIsArr = "map[string]"
}
var suffix string = "(" + isArr + ep.outputType + ")# with one(" + isArr + ep.outputType + ") return parameter."
if ep.requestMethod == POST || ep.requestMethod == PUT || ep.requestMethod == PATCH {
str = "PostData " + postIsArr + ep.postdataType
if ep.paramLen > 0 {
str += ", "
}
}
if ep.requestMethod == POST || ep.requestMethod == PUT || ep.requestMethod == PATCH || ep.requestMethod == DELETE {
suffix = "# with no return parameters."
}
if ep.isVariableLength {
str += "varArgs ..." + ep.params[0].typeName + ","
} else {
for i := 0; i < ep.paramLen; i++ {
str += ep.params[i].name + " " + ep.params[i].typeName + ","
}
}
for i := 0; i < len(ep.queryParams); i++ {
str += ep.queryParams[i].name + " " + ep.queryParams[i].typeName + ","
}
str = strings.TrimRight(str, ",")
return "No matching Method found for EndPoint:[" + f.Name + "],type:[" + ep.requestMethod + "] . Expecting: #func(serv " + t.Name() + ") " + methodName + "(" + str + ")" + suffix
}
//Runtime functions below:
//-----------------------------------------------------------------------------------------------------------------
func prepareServe(context *Context, ep endPointStruct) ([]byte, restStatus) {
servMeta := _manager().getType(ep.parentTypeName)
//Check Authorization
if servMeta.realm != "" {
if context.xsrftoken != "" {
inRealm, inRole, sess := GetAuthorizer(servMeta.realm)(context.xsrftoken, ep.role)
context.relSessionData = sess
if ep.role != "" {
if inRealm && inRole {
goto Run
}
} else {
if inRealm {
goto Run
}
}
}
return nil, restStatus{403, "Request denied, please ensure correct authentication and authorization."}
}
Run:
t := reflect.TypeOf(servMeta.template).Elem() //Get the type first, and it's pointer so Elem(), we created service with new (why??)
servVal := reflect.New(t).Elem() //Key to creating new instance of service, from the type above
//Set the Context; the user can get the context from her services function param
servVal.FieldByName("RestService").FieldByName("Context").Set(reflect.ValueOf(context))
arrArgs := make([]reflect.Value, 0)
targetMethod := servVal.Type().Method(ep.methodNumberInParent)
//For POST and PUT, make and add the first "postdata" argument to the argument list
if ep.requestMethod == POST || ep.requestMethod == PUT || ep.requestMethod == PATCH {
//Get postdata here
//TODO: Also check if this is a multipart post and handle as required.
buf := new(bytes.Buffer)
io.Copy(buf, context.request.Body)
body := buf.String()
//println("This is the body of the post:",body)
if v, state := makeArg(body, targetMethod.Type.In(1), servMeta.consumesMime); state.httpCode != http.StatusBadRequest {
arrArgs = append(arrArgs, v)
} else {
return nil, state
}
}
if len(context.args) == ep.paramLen || (ep.isVariableLength && ep.paramLen == 1) {
startIndex := 1
if ep.requestMethod == POST || ep.requestMethod == PUT || ep.requestMethod == PATCH {
startIndex = 2
}
if ep.isVariableLength {
varSliceArgs := reflect.New(targetMethod.Type.In(startIndex)).Elem()
for ij := 0; ij < len(context.args); ij++ {
dat := context.args[string(ij)]
if v, state := makeArg(dat, targetMethod.Type.In(startIndex).Elem(), servMeta.consumesMime); state.httpCode != http.StatusBadRequest {
varSliceArgs = reflect.Append(varSliceArgs, v)
} else {
return nil, state
}
}
arrArgs = append(arrArgs, varSliceArgs)
} else {
//Now add the rest of the PATH arguments to the argument list and then call the method
// GET and DELETE will only need these arguments, not the "postdata" one in their method calls
for _, par := range ep.params {
dat := ""
if str, found := context.args[par.name]; found {
dat = str
}
if v, state := makeArg(dat, targetMethod.Type.In(startIndex), servMeta.consumesMime); state.httpCode != http.StatusBadRequest {
arrArgs = append(arrArgs, v)
} else {
return nil, state
}
startIndex++
}
}
//Query arguments are not compulsory on query, so the caller may ommit them, in which case we send a zero value f its type to the method.
//Also they may be sent through in any order.
for _, par := range ep.queryParams {
dat := ""
if str, found := context.queryArgs[par.name]; found {
dat = str
}
if v, state := makeArg(dat, targetMethod.Type.In(startIndex), servMeta.consumesMime); state.httpCode != http.StatusBadRequest {
arrArgs = append(arrArgs, v)
} else {
return nil, state
}
startIndex++
}
//Now call the actual method with the data
var ret []reflect.Value
if ep.isVariableLength {
ret = servVal.Method(ep.methodNumberInParent).CallSlice(arrArgs)
} else {
ret = servVal.Method(ep.methodNumberInParent).Call(arrArgs)
}
if len(ret) == 1 { //This is when we have just called a GET
//At this stage we should be ready to write the response to client
if bytarr, err := InterfaceToBytes(ret[0].Interface(), servMeta.producesMime); err == nil {
return bytarr, restStatus{http.StatusOK, ""}
} else {
//This is an internal error with the registered marshaller not being able to marshal internal structs
return nil, restStatus{http.StatusInternalServerError, "Internal server error. Could not Marshal/UnMarshal data: " + err.Error()}
}
} else {
return nil, restStatus{http.StatusOK, ""}
}
}
//Just in case the whole civilization crashes and it falls thru to here. This shall never happen though... well tested
log.Panic("There was a problem with request handing. Probably a bug, please report.") //Add client data, and send support alert
return nil, restStatus{http.StatusInternalServerError, "GoRest: Internal server error."}
}
func makeArg(data string, template reflect.Type, mime string) (reflect.Value, restStatus) {
i := reflect.New(template).Interface()
if data == "" {
return reflect.ValueOf(i).Elem(), restStatus{http.StatusOK, ""}
}
/*else{
log.Println("Data sent: ",data)
}*/
buf := bytes.NewBufferString(data)
err := BytesToInterface(buf, i, mime)
if err != nil {
return reflect.ValueOf(nil), restStatus{http.StatusBadRequest, "Error Unmarshalling data using " + mime + ". Client sent incompetible data format in entity. (" + err.Error() + ")"}
}
return reflect.ValueOf(i).Elem(), restStatus{http.StatusOK, ""}
}