-
Notifications
You must be signed in to change notification settings - Fork 4
/
host.go
566 lines (536 loc) · 15 KB
/
host.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
package webapi
import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
)
var (
//internalControllerMethods A convenient dictionary of internal usage method fields
internalControllerMethods = map[string]bool{}
bodyTypes = map[reflect.Kind]bool{
reflect.Slice: true,
reflect.Array: true,
reflect.Map: true,
reflect.Ptr: true,
reflect.Interface: true,
}
//supported http request methods dictionary
supportedMthods = map[string]bool{
http.MethodConnect: true,
http.MethodDelete: true,
http.MethodGet: true,
http.MethodHead: true,
http.MethodOptions: true,
http.MethodPatch: true,
http.MethodPost: true,
http.MethodPut: true,
http.MethodTrace: true,
}
)
func init() {
//generate method keyword dictionary from Controller
t := types.Controller
for index := 0; index < t.NumMethod(); index++ {
internalControllerMethods[t.Method(index).Name] = true
}
}
type (
//Host Service for HTTP
Host struct {
handlers map[string]*endpoint
conf Config
errList []error
//Stack data
paths []string
global httpHandler
mstack []Middleware
}
//Config Configuration
Config struct {
//UseLowerLetter Use lower letter in path
UseLowerLetter bool
//AliasTagName Replace the system rule name with the provided name, default is "api"
AliasTagName string
//HTTPMethodTagName Specify the specific method for the endpoint, default is "options"
HTTPMethodTagName string
//CustomisedPlaceholder Used to specify where the parameters should be in the URL. The specified string will quoted by {}.
//E.G.: param -> {param}
CustomisedPlaceholder string
//AutoReport This option will display route table after successful registration
DisableAutoReport bool
}
)
//NewHost Create a new service host
func NewHost(conf Config, middlewares ...Middleware) (host *Host) {
host = &Host{
handlers: map[string]*endpoint{},
conf: conf,
global: pipeline(nil, middlewares...),
mstack: middlewares,
}
if !conf.DisableAutoReport {
os.Stdout.WriteString("Registration Info:\r\n")
}
host.initCheck()
return
}
//ServeHTTP service http request
func (host *Host) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer r.Body.Close()
}
ctx := &Context{
w: w,
r: r,
Deserializer: Serializers[strings.Split(r.Header.Get("Content-Type"), ";")[0]],
}
collection := host.handlers[strings.ToUpper(r.Method)]
var run, args = host.global, []string{}
if collection != nil {
var path = strings.TrimSpace(r.URL.Path)
// if host.conf.UseLowerLetter {
// path = strings.ToLower(path)
// }
handler, arguments := collection.Search(path, host.conf.UseLowerLetter)
if handler != nil {
run = handler.(httpHandler)
args = arguments
}
}
if run != nil {
run(ctx, args...)
}
if ctx.statuscode == 0 {
ctx.Reply(http.StatusNotFound, http.StatusText(http.StatusNotFound))
}
}
//Use Add middlewares into host
func (host *Host) Use(middlewares ...Middleware) *Host {
if len(middlewares) > 0 {
host.mstack = append(host.mstack, middlewares...)
}
host.global = pipeline(host.global, middlewares...)
return host
}
//Group Set prefix to endpoints
func (host *Host) Group(basepath string, register func(), middlewares ...Middleware) {
{
host.initCheck()
if len(basepath) > 0 && basepath[0] == '/' {
basepath = basepath[1:]
}
orginalPaths, orginalStack := host.paths, host.mstack
defer func() {
//还原栈
host.mstack, host.paths = orginalStack, orginalPaths
}()
}
//处理基地址问题
host.mstack = append(host.mstack, middlewares...)
host.paths = append(host.paths, basepath)
register()
}
//Register Register the controller with the host
func (host *Host) Register(basepath string, controller Controller, middlewares ...Middleware) (err error) {
var paths = append(host.paths, basepath)
{
host.initCheck()
defer func() {
if err != nil {
host.errList = append(host.errList, err)
}
}()
if len(host.mstack) > 0 {
//stack data will used to set prior middlewares
middlewares = append(host.mstack, middlewares...)
}
}
typ := reflect.TypeOf(controller)
controllerbasepath, semantics := host.getBasePath(controller)
//check prefix request parameters
var contextArgs []reflect.Type
var ctxPaths []string
contextArgs, ctxPaths, err = getControllerArguments(controller)
if err == nil {
controllerbasepath, _ = host.finalMethodPath(controllerbasepath, ctxPaths)
}
if err != nil {
return
}
paths = append(paths, controllerbasepath)
for index := 0; index < typ.NumMethod(); index++ {
//register all open methods.
method := typ.Method(index)
if internalControllerMethods[method.Name] || (method.Name == "Init" && contextArgs != nil) {
//a special keyword flushed
continue
}
var ep *function
var methods map[string][]string
var appendix []string
ep, methods, appendix, err = host.getMethodArguments(method, contextArgs, semantics)
if err != nil {
return
}
for option, endpoints := range methods {
handler := ep.MakeHandler()
for i, path := range endpoints {
if len(path) > 0 {
path = strings.Join(append(paths, path), "/")
} else {
path = strings.Join(paths, "/") + path
}
path, err = host.finalMethodPath(path, appendix)
if err != nil {
return
}
if _, existed := host.handlers[option]; !existed {
host.handlers[option] = &endpoint{}
}
if err = host.handlers[option].Add(path, pipeline(handler, middlewares...)); err != nil {
if index > 0 {
//if the alias is already existed,
//jump it directly.
continue
}
return
}
if !host.conf.DisableAutoReport {
//only 4 letters will be displayed if autoreport
methodprefix := fmt.Sprintf("[%4s]", smallerMethod(option))
if i > 0 {
//it is said that the method will serve as 2 or more endpoints
methodprefix = fmt.Sprintf("%6s", ` ↘`)
}
os.Stdout.WriteString(fmt.Sprintf("%s\t%s\r\n", methodprefix, path))
}
}
}
}
return
}
//AddEndpoint Register the endpoint with the host
func (host *Host) AddEndpoint(method string, path string, handler HTTPHandler, middlewares ...Middleware) (err error) {
{
host.initCheck()
path = strings.Join(append(host.paths, formatPath(path, true)), "/")
defer func() {
if err != nil {
host.errList = append(host.errList, err)
}
}()
}
if _, existed := host.handlers[method]; !existed {
host.handlers[method] = &endpoint{}
}
if len(host.mstack) > 0 {
middlewares = append(host.mstack, middlewares...)
}
path = "/" + path
err = host.handlers[method].Add(path, pipeline(func(context *Context, _ ...string) {
handler(context)
}, middlewares...))
if !host.conf.DisableAutoReport {
if len(path) == 0 {
path = "/"
}
os.Stdout.WriteString(fmt.Sprintf("[%4s]\t%s\r\n", method, path))
}
return
}
//Errors Return server build time error
func (host *Host) Errors() []error {
return host.errList
}
func (host *Host) initCheck() {
if len(host.conf.AliasTagName) == 0 {
host.conf.AliasTagName = "api"
}
if len(host.conf.HTTPMethodTagName) == 0 {
host.conf.HTTPMethodTagName = "options"
}
if len(host.conf.CustomisedPlaceholder) == 0 {
host.conf.CustomisedPlaceholder = "param"
}
if host.handlers == nil {
host.handlers = map[string]*endpoint{}
host.errList = make([]error, 0)
}
}
//pipeline create httpHandler with handler and middlewares (Recursive)
func pipeline(handler httpHandler, middlewares ...Middleware) httpHandler {
if len(middlewares) == 0 {
return handler
}
middleware := middlewares[len(middlewares)-1]
middlewares = middlewares[:len(middlewares)-1]
complexHandler := func(ctx *Context, args ...string) {
//create a composite pipeline using middleware
middleware.Invoke(ctx, func(arguments ...string) HTTPHandler {
if handler == nil {
return func(*Context) {}
}
return func(context *Context) {
handler(context, arguments...)
}
}(args...))
}
return pipeline(complexHandler, middlewares...)
}
func getReplacer(typ reflect.Type) (string, error) {
var name string
switch typ.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int16, reflect.Int8, reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
name = "{digits}"
break
case reflect.Float32, reflect.Float64:
name = "{float}"
break
case reflect.Bool:
name = "{bool}"
break
case reflect.String:
name = "{string}"
break
}
if len(name) == 0 {
return "", errors.New("cannot accpet type '" + typ.Kind().String() + "'")
}
return name, nil
}
func (host *Host) getBasePath(controller Controller) (basepath string, semantics bool) {
{
host.initCheck()
basepath = "/"
}
typ := reflect.TypeOf(controller)
for typ.Kind() == reflect.Ptr {
//need element not reference
typ = typ.Elem()
}
found := false
for index := 0; index < typ.NumField(); index++ {
field := typ.Field(index)
if !found {
if alias, hasalias := field.Tag.Lookup(host.conf.AliasTagName); hasalias {
basepath += strings.Split(alias, ",")[0]
found = true
}
}
if !semantics {
_, semantics = field.Tag.Lookup("semantics")
}
if found && semantics {
break
}
}
if !found {
name := typ.Name()
ctrlname := strings.ToLower(name)
if location := strings.LastIndex(ctrlname, "controller"); location != -1 {
name = name[:location]
ctrlname = ctrlname[:location]
}
if ctrlname == "home" {
name = ""
}
basepath += name
}
return
}
func getControllerArguments(controller Controller) ([]reflect.Type, []string, error) {
var address = make([]string, 0)
typ := reflect.TypeOf(controller)
initFunc, existed := typ.MethodByName("Init")
var contextArgs []reflect.Type
if existed && (initFunc.Type.NumOut() == 1 && initFunc.Type.Out(0) == types.Error) {
contextArgs = []reflect.Type{}
//find out all the initialization parameters and record them.
for index := 1; index < initFunc.Type.NumIn(); index++ {
arg := initFunc.Type.In(index)
name, err := getReplacer(arg)
if err != nil {
return nil, nil, err
}
address = append(address, name)
contextArgs = append(contextArgs, arg)
}
}
return contextArgs, address, nil
}
func (host *Host) getMethodArguments(method reflect.Method, contextArgs []reflect.Type, semantics bool) (*function, map[string][]string, []string, error) {
var hasBody, hasQuery bool
inputArgsCount := method.Type.NumIn()
ep := function{
//created function entity to ready the endpoint
Function: method.Func,
ContextArgs: contextArgs,
Context: method.Type.In(0),
Args: make([]*param, 0),
}
var paths []string
var methods []string
var appendix []string
for argindex := 1; argindex < inputArgsCount; argindex++ {
arg := method.Type.In(argindex)
//If a parameter is a reference, it should be treated as the body structure
isBody := bodyTypes[arg.Kind()]
if isBody || arg.Kind() == reflect.Struct {
//these logics are test the request forms, it might be existed in
//both query and body structures
argPaths, argMethods := host.getMethodPath(arg)
paths = append(paths, argPaths...)
methods = append(methods, argMethods...)
}
if isBody {
if hasBody {
return nil, nil, nil, errors.New("cannot assign 2 sets from body")
}
ep.Args = append(ep.Args, ¶m{
Type: arg,
isBody: true,
})
hasBody = true
} else if arg.Kind() == reflect.Struct {
if hasQuery {
return nil, nil, nil, errors.New("cannot assign 2 sets from query")
}
ep.Args = append(ep.Args, ¶m{
Type: arg,
isQuery: true,
})
hasQuery = true
} else {
name, err := getReplacer(arg)
if err != nil {
return nil, nil, nil, err
}
ep.Args = append(ep.Args, ¶m{
Type: arg,
})
appendix = append(appendix, name)
}
}
//If the method is not explicitly declared,
//then fall back to the default rule to register the node.
var detectedmethod, detectedname = "", method.Name
if semantics {
detectedmethod, detectedname = detectMethod(method.Name)
if len(detectedmethod) > 0 {
methods = append(methods, detectedmethod)
}
}
if len(paths) == 0 {
paths = []string{detectedname}
if strings.ToLower(detectedname) == "index" {
//if the method is named of 'Index'
//both "/Index" and "/" paths will assigned to this method
paths = append(paths, "/")
}
}
if len(methods) == 0 {
if hasBody {
//body existed might be POST
methods = []string{http.MethodPost}
} else {
//no body might be GET
methods = []string{http.MethodGet}
}
}
options := make(map[string][]string, len(methods))
var index = 0
for _, option := range methods {
options[option] = paths
index++
}
return &ep, options, appendix, nil
}
func detectMethod(name string) (method, path string) {
path = name
for supportedmethod := range supportedMthods {
if strings.HasPrefix(strings.ToLower(name), strings.ToLower(supportedmethod)) {
method, path = supportedmethod, name[len(supportedmethod):]
return
}
}
return
}
func (host *Host) finalMethodPath(path string, appendix []string) (string, error) {
var endwithslash = strings.HasSuffix(path, "/") || strings.HasSuffix(path, "\\")
if path = "/" + filepath.ToSlash(formatPath(path)); endwithslash && len(path) > 1 {
path += "/"
}
for {
where := strings.Index(path, "{"+host.conf.CustomisedPlaceholder+"}")
if len(appendix) != 0 && where != -1 {
path = strings.Replace(path, "{"+host.conf.CustomisedPlaceholder+"}", appendix[0], 1)
appendix = appendix[1:]
} else {
break
}
}
if len(appendix) == 0 {
if strings.Contains(path, "{"+host.conf.CustomisedPlaceholder+"}") {
return "", errors.New("cannot match " + path + " according to the params")
}
}
if suffix := strings.Join(appendix, "/"); len(suffix) > 0 {
path += "/" + suffix
}
if host.conf.UseLowerLetter {
path = strings.ToLower(path)
}
return path, nil
}
func (host *Host) getMethodPath(arg reflect.Type) (paths, options []string) {
//these logics are test the request forms, it might be existed in
//both query and body structures
for arg.Kind() == reflect.Ptr {
//the flowing require element not reference
arg = arg.Elem()
}
if arg.Kind() != reflect.Struct {
return
}
var methods = map[string]bool{}
for i := 0; i < arg.NumField(); i++ {
field := arg.Field(i)
if alias, hasalias := field.Tag.Lookup(host.conf.AliasTagName); hasalias {
paths = append(paths, strings.Split(alias, ",")...)
}
if options, hasoptions := field.Tag.Lookup(host.conf.HTTPMethodTagName); hasoptions {
for _, option := range strings.Split(options, ",") {
option = strings.ToUpper(option)
if supportedMthods[option] {
methods[option] = true
}
}
}
}
options = make([]string, len(methods))
var index = 0
for option := range methods {
options[index] = option
index++
}
return
}
func smallerMethod(method string) string {
if len(method) > 4 {
method = method[:4]
}
return method
}
func formatPath(path string, skipsuffix ...bool) string {
path = regexp.MustCompile(`[\\/]{1,}`).ReplaceAllString(path, "/")
path = strings.TrimLeft(path, "/")
if len(skipsuffix) == 0 || !skipsuffix[0] {
path = strings.TrimRight(path, "/")
}
return path
}